text:
using JuMP, EAGO

                     m = Model()

                     EAGO.register_eago_operators!(m)

                     @variable(m, -1 <= x[i=1:5] <= 1)

                     @variable(m, -140.37215752831116 <= q <= 140.41841564400983)

                     add_NL_constraint(m, :(gelu(0.9038900968817085 + 0.1284043831226005*gelu(0.06165362792774953 + 0.6866075626761576*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.8737233458006566*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.3942911833193632*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.6872447034250162*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5711071882051262*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.26042276084039084*gelu(0.8058455478649482 + 0.7751639240502244*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.13474005943220124*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.6437669970537465*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.5932192098608322*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5325023046383324*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.6458808355119907*gelu(-0.1540966309548315 + 0.690406062481447*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.4718956794952942*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.8703243890856593*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.8079540211479861*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.683716372184894*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.6567358944011805*gelu(-0.2486694730930381 + -0.9006272851005916*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.9841514005441985*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.7501520395123897*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.43486617405885397*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + -0.4797454164387962*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.41502277707459934*gelu(-0.9928729682863509 + 0.9588446333785003*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.7154937103302039*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.17921833371514895*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.7009330672719543*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.15311755902026114*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5])))) + gelu(-0.8820041740138964 + 0.8813585352462416*gelu(0.06165362792774953 + 0.6866075626761576*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.8737233458006566*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.3942911833193632*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.6872447034250162*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5711071882051262*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.30334290832683886*gelu(0.8058455478649482 + 0.7751639240502244*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.13474005943220124*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.6437669970537465*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.5932192098608322*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5325023046383324*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.6303754843616343*gelu(-0.1540966309548315 + 0.690406062481447*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.4718956794952942*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.8703243890856593*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.8079540211479861*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.683716372184894*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.9344814932534002*gelu(-0.2486694730930381 + -0.9006272851005916*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.9841514005441985*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.7501520395123897*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.43486617405885397*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + -0.4797454164387962*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.8925753470795712*gelu(-0.9928729682863509 + 0.9588446333785003*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.7154937103302039*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.17921833371514895*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.7009330672719543*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.15311755902026114*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5])))) + gelu(-0.6413973695460733 + -0.5291254814289021*gelu(0.06165362792774953 + 0.6866075626761576*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.8737233458006566*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.3942911833193632*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.6872447034250162*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5711071882051262*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.3315514300310589*gelu(0.8058455478649482 + 0.7751639240502244*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.13474005943220124*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.6437669970537465*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.5932192098608322*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5325023046383324*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.9076257425527015*gelu(-0.1540966309548315 + 0.690406062481447*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.4718956794952942*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.8703243890856593*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.8079540211479861*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.683716372184894*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.9763381142518175*gelu(-0.2486694730930381 + -0.9006272851005916*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.9841514005441985*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.7501520395123897*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.43486617405885397*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + -0.4797454164387962*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.06362970408750801*gelu(-0.9928729682863509 + 0.9588446333785003*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.7154937103302039*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.17921833371514895*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.7009330672719543*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.15311755902026114*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5])))) + gelu(0.9122346082558659 + 0.2864216745322903*gelu(0.06165362792774953 + 0.6866075626761576*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.8737233458006566*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.3942911833193632*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.6872447034250162*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5711071882051262*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.7014729451110155*gelu(0.8058455478649482 + 0.7751639240502244*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.13474005943220124*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.6437669970537465*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.5932192098608322*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5325023046383324*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.27913045286088156*gelu(-0.1540966309548315 + 0.690406062481447*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.4718956794952942*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.8703243890856593*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.8079540211479861*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.683716372184894*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.014698309183167169*gelu(-0.2486694730930381 + -0.9006272851005916*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.9841514005441985*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.7501520395123897*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.43486617405885397*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + -0.4797454164387962*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + -0.9872323021033105*gelu(-0.9928729682863509 + 0.9588446333785003*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.7154937103302039*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.17921833371514895*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.7009330672719543*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.15311755902026114*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5])))) + gelu(0.6835137249354726 + 0.06184589975771315*gelu(0.06165362792774953 + 0.6866075626761576*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.8737233458006566*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.3942911833193632*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.6872447034250162*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5711071882051262*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.6514470819403977*gelu(0.8058455478649482 + 0.7751639240502244*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.13474005943220124*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.6437669970537465*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + 0.5932192098608322*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.5325023046383324*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.1907919388573478*gelu(-0.1540966309548315 + 0.690406062481447*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.4718956794952942*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.8703243890856593*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.8079540211479861*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.683716372184894*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.3162639033084287*gelu(-0.2486694730930381 + -0.9006272851005916*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + -0.9841514005441985*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + 0.7501520395123897*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.43486617405885397*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + -0.4797454164387962*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5]))) + 0.2338844135686573*gelu(-0.9928729682863509 + 0.9588446333785003*gelu(0.28804974063451105 + 0.7911631812636903*$(x[1]) + 0.6415196610101699*$(x[2]) + -0.09319048786154349*$(x[3]) + 0.5261383650120517*$(x[4]) + -0.5505775194565721*$(x[5])) + 0.7154937103302039*gelu(0.7342872210188394 + 0.669146525148411*$(x[1]) + 0.2634123220650846*$(x[2]) + -0.9804313836692913*$(x[3]) + 0.770312239258653*$(x[4]) + 0.24263357188873957*$(x[5])) + -0.17921833371514895*gelu(-0.6886620050375161 + 0.8091467022606786*$(x[1]) + 0.910808980108254*$(x[2]) + -0.3183669784784451*$(x[3]) + 0.5442365253482557*$(x[4]) + -0.6054042374016482*$(x[5])) + -0.7009330672719543*gelu(0.5813944367886887 + 0.520001186683257*$(x[1]) + -0.3951433421155799*$(x[2]) + 0.803037085072233*$(x[3]) + 0.9067157149850686*$(x[4]) + 0.001120584088625698*$(x[5])) + 0.15311755902026114*gelu(-0.16131179027810427 + 0.7148051479719681*$(x[1]) + 0.7364049274130124*$(x[2]) + -0.647777979207961*$(x[3]) + 0.24628792618437867*$(x[4]) + 0.6449790156418587*$(x[5])))) - $q <= 0.0))

                     @objective(m, Min, q)

                     return m

max_stars_repo_name: PSORLab/RSActivationFunctions

max_issues_repo_name: PSORLab/RSActivationFunctions

max_forks_repo_name: PSORLab/RSActivationFunctions


text:
type IpAddress
    a_0::Cchar
    a_1::Cchar
    a_2::Cchar
    a_3::Cchar
    a_4::Cchar
    a_5::Cchar
    a_6::Cchar
    a_7::Cchar
    a_8::Cchar
    a_9::Cchar
    a_10::Cchar
    a_11::Cchar
    a_12::Cchar
    a_13::Cchar
    a_14::Cchar
    a_15::Cchar
end

function IpAddress(address::AbstractString)
    return ccall((:sfIpAddress_fromString, libcsfml_network), IpAddress, (Ptr{Cchar},), address)
end

function to_string(a::IpAddress)
        "$(Char(a.a_0))$(Char(a.a_1))$(Char(a.a_2))$(Char(a.a_3))$(Char(a.a_4))$(Char(a.a_5))$(Char(a.a_6))$(Char(a.a_7))$(Char(a.a_8))$(Char(a.a_9))$(Char(a.a_10))$(Char(a.a_11))$(Char(a.a_12))$(Char(a.a_13))$(Char(a.a_14))$(Char(a.a_15))"
end

ext: jl


text:
export verify

function verify(mod::Module)
    out_error = Ref{Cstring}()
    status =
        convert(Core.Bool, API.LLVMVerifyModule(ref(mod), API.LLVMReturnStatusAction, out_error))

    if status
        error = unsafe_string(out_error[])
        API.LLVMDisposeMessage(out_error[])
        throw(LLVMException(error))
    end
end

function verify(f::Function)
    status = convert(Core.Bool, API.LLVMVerifyFunction(ref(f), API.LLVMReturnStatusAction))

    if status
        throw(LLVMException("broken function"))
    end
end


text:
using VegaLite
using DataFrames

# a simple histogram of random standard normal draws

data_values(DataFrame(x=randn(200))) +
    mark_bar() +
    encoding_x_quant(:x; bin=Dict(:maxbins=>20), axis=Dict(:title=>"values")) +
    encoding_y_quant(:*, aggregate="count", axis=Dict(:title=>"number of draws"))


text:
import ExprTools

macro dec(decorator, inner_def)
    inner_def = ExprTools.splitdef(inner_def)
    outer_def = copy(inner_def)
    fname = get(inner_def, :name, nothing)
    if fname !== nothing
        @assert fname isa Symbol
        inner_def[:name] = Symbol(fname, :_inner)
    end
    outer_def[:body] = Expr(:call,
        :($decorator($(ExprTools.combinedef(inner_def)))),
        get(outer_def, :args, [])...,
        get(outer_def, :kwargs, [])...,
    )
    return esc(ExprTools.combinedef(outer_def))
end

_time(f) = (x...) -> (
    t0=time();
    fun_name = String(Symbol(f));
    println("begin ",fun_name);
    val=f(x...);
    println("end ",fun_name);
    println(fun_name," took ", time()-t0, " s");
    val
    )


text:
# helper functions

"""
    CCDReduction.getdata(::FITSIO.ImageHDU)

Loads the given HDU as an `Array`, permuting the dimensions appropriately.

FITSIO.jl takes over memory read in by cfitsio, which reads in row-major form, whereas when Julia takes that memory, it is assumed as column major.
Therefore all data read by [`FITSIO.read`](http://juliaastro.github.io/FITSIO.jl/latest/api.html#Base.read-Tuple{ImageHDU}) is transposed. This function allows the user to read data in a consistent way to `Array` by transposing after reading.
"""
function getdata(hdu::ImageHDU)
    data = read(hdu)
    d = ndims(data)
    return permutedims(data, d:-1:1)
end

#---------------------------------------------------------------------------------------
# Code generation with codegen to support path of FITS files
for func in (:flat_correct, :subtract_bias, :subtract_dark)
    @eval $func(frame::String, correction; hdu = 1, kwargs...) = $func(CCDData(frame; hdu = hdu), correction; kwargs...)
    @eval $func(frame, correction::String; hdu = 1, kwargs...) = $func(frame, CCDData(correction; hdu = hdu); kwargs...)
    @eval begin
        function $func(frame::String, correction::String; hdu = (1, 1), kwargs...)
            hdus = hdu isa Integer ? (hdu, hdu) : hdu
            return $func(CCDData(frame; hdu = hdus[1]), CCDData(frame; hdu = hdus[2]); kwargs...)
        end
    end
end

for func in (:flat_correct!, :subtract_bias!, :subtract_dark!)
    @eval $func(frame::AbstractArray, correction::String; hdu = 1, kwargs...) = $func(frame, CCDData(correction; hdu = hdu); kwargs...)
end

for func in (:crop, :trim, :subtract_overscan)
    @eval $func(frame::AbstractString, args...; hdu = 1, kwargs...) = $func(CCDData(frame; hdu = hdu), args...; kwargs...)
end

# separate function for combine involving CCDData because of custom header copying
function combine(frames::Vararg{<:CCDData{<:Number}}; header_hdu = 1, kwargs...)
    data_arrays = map(frame -> data(frame), frames)
    processed_frame = combine(data_arrays...; kwargs...)
    return CCDData(processed_frame, deepcopy(hdr(frames[header_hdu])))
end

# String supporting version of combine
function combine(frames::Vararg{AbstractString, N}; hdu = ntuple(one, N), kwargs...) where N
    ccddata_frames = map(zip(frames, hdu)) do (frame, hdu_idx)
        CCDData(frame; hdu = hdu_idx)
    end
    return combine(ccddata_frames...; kwargs...)
end


text:
module SIMDPirates

using VectorizationBase
using VectorizationBase:
    llvmtype, AbstractSIMDVector, SVec, vbroadcast, vzero, vone, _MM, _Vec,
    AbstractPointer, AbstractInitializedPointer, AbstractStridedPointer, JuliaPointerType, AbstractStructVec
import VectorizationBase: vload, vstore!, vnoaliasstore!, AbstractMask, tomask, IntTypes, UIntTypes, IntegerTypes, FloatingTypes, ScalarTypes, vadd, vmul, vsub, vleft_bitshift, NativeTypes#, vright_bitshift
using Base: llvmcall
# @inline llvmcall(s::String, args...) = Base.llvmcall(s, args...)
# @inline llvmcall(s::Tuple{String,String}, args...) = Base.llvmcall(s, args...)

export  Vec, SVec, VE, _MM, stridedpointer,
    extract_data, vbroadcast, vconvert,
    vload, vloada, vstore!, vstorea!, vstorent!, shufflevector,
    vifelse, Mask,
    vfma, vmuladd,
    vsqrt, rsqrt, vinv, vabs2,
    vadd, vsub, vmul, vfdiv, vsum, vprod,
    vnmul, vnsub,
    vfmadd, vfnmadd, vfmsub, vfnmsub,
    vfmadd_fast, vfnmadd_fast, vfmsub_fast, vfnmsub_fast,
    gather, scatter!,
    addscalar,
    @pirate

vecarguments(args) = [isa(arg, Symbol) ? :($arg::_Vec{W,T}) : arg for arg ∈ args]
function structvecarguments(args)
    asa = Expr[]
    sva = Expr[]
    rna = Expr[]
    for arg ∈ args
        if isa(arg, Symbol)
            rarg = gensym(arg)
            push!(asa, Expr(:(::), rarg, :(AbstractStructVec{W,T})))
            push!(sva, Expr(:(::), rarg, :(SVec{W,T})))
            push!(rna, Expr(:(=), arg, Expr(:call, :extract_data, rarg)))
        elseif length(arg.args) == 2
            arg = copy(arg)
            narg = arg.args[1]
            rarg = gensym(narg)
            arg.args[1] = rarg
            push!(asa, arg)
            push!(sva, arg)
            push!(rna, Expr(:(=), narg, Expr(:call, :vconvert, :(Vec{W,T}), rarg)))
        else
            push!(asa, arg)
            push!(sva, arg)
        end
    end
    asa, sva, rna
end
function vector_args(args)
    vecargs = vecarguments(args)
    asargs, structargs, renamedargs = structvecarguments(args)
    vecargs, asargs, structargs, renamedargs
end

function parse_func_decl(expr::Expr)
    @assert (expr.head === :(=) || expr.head === :function) "Failed to match function declaration: $expr."
    w = expr.args[1]
    body = expr.args[2]
    WT = @view(w.args[2:end])
    func = first(w.args)
    f = first(func.args)
    args = @view(func.args[2:end])
    f, args, WT, body
end
macro vectordef(rename, expr)
    f, args, R, body = parse_func_decl(expr)
    vecargs, asargs, structargs, renamedargs = vector_args(args)
    push!(renamedargs, Expr(:call, Expr(:curly, :SVec, :W), body))
    q = quote
        @inline $rename($(vecargs...)) where {$(R...)} = $body
        @inline function $f($(asargs...)) where {$(R...)}
            $(renamedargs...)
        end
        @inline function $f($(structargs...)) where {$(R...)}
            $(renamedargs...)
        end
    end
    esc(q)
end
macro evectordef(rename, expr)
    f, args, R, body = parse_func_decl(expr)
    vecargs, abstractargs, structargs, renamedargs = vector_args(args)
    push!(renamedargs, Expr(:call, Expr(:curly, :SVec, :W), body))
    q = quote
        @inline $rename($(vecargs...)) where {$(R...)} = $body
        @inline function $rename($(abstractargs...)) where {$(R...)}
            $(renamedargs...)
        end
    end
    esc(q)
end

macro vpromote(f, N)
    argnames = [Symbol(:v_, n) for n ∈ 1:N]
    types = [Symbol(:V, n) for n ∈ 1:N]
    args = [Expr(:(::), a, t) for (a,t) ∈ zip(argnames, types)]
    svecargs = [Expr(:(::), a, Expr(:curly, :SVec, :W, :T)) for a ∈ argnames]
    q = quote
        @inline function $f($(args...)) where {$(types...)}
            V = promote_vtype($(types...))
            $(Expr(:call, f, [ Expr(:call, :vconvert, :V, arg) for arg ∈ argnames  ]... ))
        end
        @inline function $f($(svecargs...)) where {W,T}
            SVec{W}($(Expr(:call, f, [ Expr(:call, :extract_data, arg) for arg ∈ argnames  ]... )))
        end
    end
    esc(q)
end

include("type_definitions.jl")
include("llvm_utils.jl")
include("llvmwrap.jl")
include("conditionals.jl")
include("integer_arithmetic.jl")
include("floating_point_arithmetic.jl")
include("vrange.jl")
include("memory.jl")
include("shufflevector.jl")
include("special.jl")
include("contract_pass.jl")
include("pirate.jl") #TODO: remove this in a future release
include("arithmeticwithconsts.jl")
# include("precompile.jl")
# _precompile_()

end # module


text:
using Select
using Base.Test

function select_block_test(t1, t2, t3, t4)
    c1 = Channel{Symbol}(1)
    c2 = Channel{Int}(1)
    c3 = Channel(1)

    put!(c3,1)

    @schedule begin
        sleep(t1)
        put!(c1,:a)
    end

    @schedule begin
        sleep(t2)
        put!(c2,1)
    end

    @schedule begin
        sleep(t3)
        take!(c3)
    end

    task = @schedule begin
        sleep(t4)
        :task_done
    end

    @select begin
        c1 |> x           => "Got $x from c1"
        c2                =>  "Got a message from c2"
        c3 <| :write_test => "Wrote to c3"
        task |> z         => begin
            "Task finished with $z"
        end
    end
end

@test select_block_test(.5, 1, 1, 1) == "Got a from c1"
@test select_block_test(1, .5, 1, 1) == "Got a message from c2"
@test select_block_test(1, 1, .5, 1) == "Wrote to c3"
@test select_block_test(1, 1, 1, .5) == "Task finished with task_done"

function select_nonblock_test(test)
    c = Channel(1)
    c2 = Channel(1)
    put!(c2, 1)
    if test == :take
        put!(c, 1)
    elseif test == :put
        take!(c2)
    elseif test == :default
    end

    @select begin
        c |> x => "Got $x from c"
        c2 <| 1 => "Wrote to c2"
        _ => "Default case"
    end
end

@test select_nonblock_test(:take) == "Got 1 from c"
@test select_nonblock_test(:put) == "Wrote to c2"
@test select_nonblock_test(:default) == "Default case"


text:
macro dimcheck(condition)
    :(($(esc(condition))) || throw(DimensionMismatch("Dimensions of the parameters don't match: $($(string(condition)))")))
end


text:
# License for this file: MIT (expat)
# Copyright 2017-2018, DLR Institute of System Dynamics and Control

module ModiaToModiaMath

import ModiaMath
using ModiaMath.DAE

mutable struct ModiaSimulationModel <: ModiaMath.AbstractSimulationModel
    modelName::String
    simulationState::ModiaMath.SimulationState
    getModiaResidues!::Function
    preInitial::Bool
    nz_preInitial::Int
    nw::Int
    store    # extra storage

    function ModiaSimulationModel(name::Symbol, f!::Function, x0::Vector{Float64}, der_x0::Vector{Float64}, jac=nothing;
                                structureOfDAE = ModiaMath.DAE_NoSpecialStructure,
                                is_constraint=fill(false,length(x0)),
								has_constraintDerivatives=false,
                                xNames::Vector{String}=ModiaMath.DAE.nameVector("x", length(x0)),
                                derxNames::Vector{String}=ModiaMath.DAE.fcNameVector("der", xNames),
                                wNames::Vector{String}=fill("", 0),
                                xw_states=fill(true, length(x0)),
                                nc=0, nz=0, maxSparsity=0.1,
                                startTime=0.0,
                                stopTime=1.0,
                                tolerance=1e-4,
                                interval=(stopTime - startTime) / 500.0)

        simulationState = ModiaMath.SimulationState(string(name), getModelResidues!, x0;
                                structureOfDAE = structureOfDAE,
                                is_constraint = is_constraint,
								has_constraintDerivatives = has_constraintDerivatives,
                                nc=nc == 0 ? 1 : nc,
                                nz=nz,
                                jac=jac,
                                scaleConstraintsAtEvents=false,
                                maxSparsity=maxSparsity,
                                defaultStartTime=startTime,
                                defaultStopTime=stopTime,
                                defaultTolerance=tolerance,
                                defaultInterval=interval)

        new(string(name), simulationState, f!, false, 0, length(wNames), nothing)
    end

    function ModiaSimulationModel(name::String,
                            getModelResidues!::Function,
                            x_start::Vector{Float64},
                            getVariableName::Function=ModiaMath.DAE.defaultVariableName;
                            structureOfDAE = ModiaMath.DAE_NoSpecialStructure,
                            is_constraint=fill(false,length(x_start)),
							has_constraintDerivatives=false,
                            nc::Int=1,
                            nz::Int=0,
                            nw::Int=0,
                            x_fixed::Vector{Bool}=fill(false, length(x_start)),
                            x_nominal::Vector{Float64}=fill(NaN, length(x_start)),
                            hev::Float64=1e-8,
                            scaleConstraintsAtEvents::Bool=false,
                            jac=nothing, maxSparsity::Float64=0.1,
                            startTime=0.0,
                            stopTime=1.0,
                            tolerance=1e-4,
                            interval=(stopTime - startTime) / 500.0)

        simulationState = ModiaMath.SimulationState(name, getModelResidues!, x_start, getVariableName;
                            structureOfDAE = structureOfDAE,
                            is_constraint = is_constraint,
							has_constraintDerivatives = has_constraintDerivatives,
                            nc=nc,
                            nz=nz,
                            nw=nw,
                            x_fixed=x_fixed,
                            x_nominal=x_nominal,
                            hev=hev,
                            scaleConstraintsAtEvents=scaleConstraintsAtEvents,
                            jac=jac,
                            maxSparsity=maxSparsity,
                            defaultStartTime=startTime,
                            defaultStopTime=stopTime,
                            defaultTolerance=tolerance,
                            defaultInterval=interval)

        new(name, simulationState, getModelResidues!, false, 0, nw, nothing)
    end

    function ModiaSimulationModel()
        function emptyFunction
        end

        simulationState = ModiaMath.DAE.SimulationState("???", emptyFunction, zeros(1))
        new("???", simulationState, emptyFunction, true, 0, 0, nothing)
    end
end

function getModelResidues!(m::ModiaSimulationModel, t::Float64, y::Vector{Float64}, yp::Vector{Float64}, residues::Vector{Float64}, w::Vector{Float64})
    m.time = t
    if m.nw == 0
        Base.invokelatest(m.getModiaResidues!, m, y, yp, residues)
    else
        Base.invokelatest(m.getModiaResidues!, m, y, yp, residues, w)
    end
end

function getRawResult(m::ModiaSimulationModel)
    sim   = m.simulationState
    res   = sim.rawResult
    nt    = res.nt
    nx    = sim.nx
    t     = @view res.data[1:nt,1]
    X     = @view res.data[1:nt,2:nx + 1]
    DER_X = @view res.data[1:nt,nx + 2:2 * nx + 1]
    W     = @view res.data[1:nt,2 * nx + 2:end]
    return (t, X, DER_X, W)
end

#export ModiaSimulationModel
#export EventRestart, NoRestart, Restart, FullRestart, Terminate
#export isPreInitial, isInitial, isEvent, isLog
#export setNextEvent!, positive!, positiveChange!, positiveEdge!

isPreInitial(m::ModiaSimulationModel) = m.preInitial
isInitial(m::ModiaSimulationModel) = ModiaMath.isInitial(m.simulationState)
isTerminal(m::ModiaSimulationModel) = ModiaMath.isTerminal(m.simulationState)
isStoreResult(m::ModiaSimulationModel) = ModiaMath.isStoreResult(m.simulationState)
isLogInfos(m::ModiaSimulationModel) = ModiaMath.isLogInfos(m.simulationState)
isLogWarnings(m::ModiaSimulationModel) = ModiaMath.isLogWarning(m.simulationState)
isLogEvents(m::ModiaSimulationModel) = ModiaMath.isLogEvents(m.simulationState)
isEvent(m::ModiaSimulationModel) = m.simulationState.eventHandler.event
isAfterSimulationStart(m::ModiaSimulationModel) = m.simulationState.eventHandler.afterSimulationStart

setNextEvent!(m::ModiaSimulationModel, nextEventTime::Float64;
              integrateToEvent::Bool=true, restart::ModiaMath.EventRestart=ModiaMath.Restart) = ModiaMath.setNextEvent!(m.simulationState.eventHandler, nextEventTime;
                                                                                integrateToEvent=integrateToEvent, restart=restart)

function positive!(crossing::Float64, m::ModiaSimulationModel, nr::Int, crossingAsString="????"; restart::ModiaMath.EventRestart=ModiaMath.Restart)
    if m.preInitial
        m.nz_preInitial = max(m.nz_preInitial, nr)
        return crossing > 0.0
    end
    ModiaMath.DAE.positive!(m.simulationState.eventHandler, nr, crossing, crossingAsString; restart=restart)
end

function positiveChange!(crossing::Float64, m::ModiaSimulationModel, nr::Int, crossingAsString="????"; restart::ModiaMath.EventRestart=ModiaMath.Restart)
    if m.preInitial
        m.nz_preInitial = max(m.nz_preInitial, nr)
        return false
    end
    ModiaMath.DAE.change!(m.simulationState.eventHandler, nr, crossing, crossingAsString="????"; restart=ModiaMath.Restart)
end

function positiveEdge!(crossing::Float64, m::ModiaSimulationModel, nr::Int, crossingAsString="????"; restart::ModiaMath.EventRestart=ModiaMath.Restart)
    if m.preInitial
        m.nz_preInitial = max(m.nz_preInitial, nr)
        return false
    end
    ModiaMath.DAE.edge!(m.simulationState.eventHandler, nr, crossing, crossingAsString="????"; restart=ModiaMath.Restart)
end

simulate(m::ModiaSimulationModel, t; log::Bool=false, tolRel::Float64=1e-4, KLUorderingChoice::Int=1) =
           simulate(m, collect(t); log=log, tolRel=tolRel, KLUorderingChoice=KLUorderingChoice)

function simulate(m::ModiaSimulationModel, t::Vector{Float64};
                  log::Bool=false,
                  tolRel::Float64=1e-4,
                  KLUorderingChoice::Int=1)
    startTime = t[1]
    stopTime = t[end]
    interval = (stopTime - startTime) / (length(t) - 1)

    ModiaMath.simulate!(m;stopTime=stopTime,
                        tolerance=tolRel,
                        startTime=startTime,
                        interval=interval,
                        log=log,
                        KLUorderingChoice=KLUorderingChoice)
end

end


text:
using Oceananigans.MultiRegion
using Oceananigans.MultiRegion: reconstruct_global_field
using Oceananigans.Grids: min_Δx, min_Δy
using Oceananigans.Operators: hack_cosd

# Tracer patch for visualization
Gaussian(x, y, L) = exp(-(x^2 + y^2) / 2L^2)

prescribed_velocities() = PrescribedVelocityFields(u=(λ, ϕ, z, t=0) -> 0.1 * hack_cosd(ϕ))

function Δ_min(grid)
    Δx_min = min_Δx(grid)
    Δy_min = min_Δy(grid)
    return min(Δx_min, Δy_min)
end

function solid_body_tracer_advection_test(grid; P = XPartition, regions = 1)

    if architecture(grid) isa GPU
        devices = (0, 0)
    else
        devices = nothing
    end
    mrg = MultiRegionGrid(grid, partition = P(regions), devices = devices)

    if grid isa RectilinearGrid
        L = 0.1
    else
        L = 24
    end

    model = HydrostaticFreeSurfaceModel(grid = mrg,
                                        tracers = (:c, :d, :e),
                                        velocities = prescribed_velocities(),
                                        free_surface = ExplicitFreeSurface(),
                                        momentum_advection = nothing,
                                        tracer_advection = WENO5(),
                                        coriolis = nothing,
                                        buoyancy = nothing,
                                        closure  = nothing)

    # Tracer patch for visualization
    Gaussian(x, y, L) = exp(-(x^2 + y^2) / 2L^2)

    # Tracer patch parameters
    cᵢ(x, y, z) = Gaussian(x, 0, L)
    dᵢ(x, y, z) = Gaussian(0, y, L)
    eᵢ(x, y, z) = Gaussian(x, y, L)

    set!(model, c=cᵢ, d=dᵢ, e=eᵢ)

    # Time-scale for tracer advection across the smallest grid cell
    advection_time_scale = Δ_min(grid) / 0.1

    Δt = 0.1advection_time_scale

    for step in 1:10
        time_step!(model, Δt)
    end

    return model.tracers
end

function solid_body_rotation_test(grid; P = XPartition, regions = 1)

    if architecture(grid) isa GPU
        devices = (0, 0)
    else
        devices = nothing
    end
    mrg = MultiRegionGrid(grid, partition = P(regions))

    free_surface = ExplicitFreeSurface(gravitational_acceleration = 1)
    coriolis     = HydrostaticSphericalCoriolis(rotation_rate = 1)

    model = HydrostaticFreeSurfaceModel(grid = mrg,
                                        momentum_advection = VectorInvariant(),
                                        free_surface = free_surface,
                                        coriolis = coriolis,
                                        tracers = :c,
                                        tracer_advection = WENO5(),
                                        buoyancy = nothing,
                                        closure = nothing)

    g = model.free_surface.gravitational_acceleration
    R = grid.radius
    Ω = model.coriolis.rotation_rate

    uᵢ(λ, φ, z) = 0.1 * cosd(φ) * sin(λ)
    ηᵢ(λ, φ)    = (R * Ω * 0.1 + 0.1^2 / 2) * sind(φ)^2 / g * sin(λ)

    cᵢ(λ, φ, z) = Gaussian(λ, φ - 5, 10)

    set!(model, u=uᵢ, η=ηᵢ, c=cᵢ)

    Δt = 0.1 * Δ_min(grid)  / sqrt(g * grid.Lz)

    for step in 1:10
        time_step!(model, Δt)
    end

    return merge(model.velocities, model.tracers, (; η = model.free_surface.η))
end

function diffusion_cosine_test(grid;  P = XPartition, regions = 1, closure, field_name = :c)
    κ, m = 1, 2 # diffusivity and cosine wavenumber

    if architecture(grid) isa GPU
        devices = (0, 0)
    else
        devices = nothing
    end
    mrg = MultiRegionGrid(grid, partition = P(regions), devices = devices)

    model = HydrostaticFreeSurfaceModel(grid = mrg,
                                        coriolis = nothing,
                                        closure = closure,
                                        tracers = :c,
                                        buoyancy=nothing)

    init(x, y, z) = cos(m * x)
    f = fields(model)[field_name]

    @apply_regionally set!(f, init)

    update_state!(model)

    # Step forward with small time-step relative to diff. time-scale
    Δt = 1e-6 * grid.Lz^2 / κ
    for n = 1:10
        time_step!(model, Δt)
    end

    return f
end

Nx = 32; Ny = 32

for arch in archs

    grid_rect = RectilinearGrid(arch, size = (Nx, Ny, 1),
                                        halo = (3, 3, 3),
                                        topology = (Periodic, Bounded, Bounded),
                                        x = (0, 1),
                                        y = (0, 1),
                                        z = (0, 1))

    grid_lat = LatitudeLongitudeGrid(arch, size = (Nx, Ny, 1),
                                        halo = (3, 3, 3),
                                        radius = 1, latitude = (-80, 80),
                                        longitude = (-180, 180), z = (-1, 0))

    partitioning = [XPartition]

    @testset "Testing multi region tracer advection" begin
        for grid in [grid_rect, grid_lat]

            cs, ds, es = solid_body_tracer_advection_test(grid)

            cs = Array(interior(cs))
            ds = Array(interior(ds))
            es = Array(interior(es))

            for regions in [2, 4], P in partitioning
                @info "  Testing $regions $(P)s on $(typeof(grid).name.wrapper) on the $arch"
                c, d, e = solid_body_tracer_advection_test(grid; P = P, regions=regions)

                c = interior(reconstruct_global_field(c))
                d = interior(reconstruct_global_field(d))
                e = interior(reconstruct_global_field(e))

                @test all(c .≈ cs)
                @test all(d .≈ ds)
                @test all(e .≈ es)
            end
        end
    end

    @testset "Testing multi region solid body rotation" begin
        grid = LatitudeLongitudeGrid(arch, size = (Nx, Ny, 1),
                                     halo = (3, 3, 3),
                                     radius = 1, latitude = (-80, 80),
                                     longitude = (-160, 160), z = (-1, 0))

        us, vs, ws, cs, ηs = solid_body_rotation_test(grid)

        us = Array(interior(us))
        vs = Array(interior(vs))
        ws = Array(interior(ws))
        cs = Array(interior(cs))
        ηs = Array(interior(ηs))

        for regions in [2, 4], P in partitioning
            @info "  Testing $regions $(P)s on $(typeof(grid).name.wrapper) on the $arch"
            u, v, w, c, η = solid_body_rotation_test(grid; P = P, regions=regions)

            u = interior(reconstruct_global_field(u))
            v = interior(reconstruct_global_field(v))
            w = interior(reconstruct_global_field(w))
            c = interior(reconstruct_global_field(c))
            η = interior(reconstruct_global_field(η))

            @test all(isapprox(u, us, atol=1e-20, rtol = 1e-15))
            @test all(isapprox(v, vs, atol=1e-20, rtol = 1e-15))
            @test all(isapprox(w, ws, atol=1e-20, rtol = 1e-15))
            @test all(isapprox(c, cs, atol=1e-20, rtol = 1e-15))
            @test all(isapprox(η, ηs, atol=1e-20, rtol = 1e-15))
        end
    end

    @testset "Testing multi region gaussian diffusion" begin
        grid  = RectilinearGrid(arch, size = (Nx, Ny, 1),
                                halo = (3, 3, 3),
                                topology = (Bounded, Bounded, Bounded),
                                x = (0, 1),
                                y = (0, 1),
                                z = (0, 1))

        diff₂ = ScalarDiffusivity(ν = 1, κ = 1)
        diff₄ = ScalarBiharmonicDiffusivity(ν = 1e-5, κ = 1e-5)

        for fieldname in [:u, :v, :c]
            for closure in [diff₂, diff₄]

                fs = diffusion_cosine_test(grid; closure, field_name = fieldname)
                fs = Array(interior(fs));

                for regions in [2, 4], P in partitioning
                    @info "  Testing diffusion of $fieldname on $regions $(P)s with $(typeof(closure).name.wrapper) on the $arch"

                    f = diffusion_cosine_test(grid; closure, P = P, field_name = fieldname, regions = regions)
                    f = interior(reconstruct_global_field(f))

                    @test all(f .≈ fs)
                end
            end
        end
    end
end


text:
using QuantumWalk
using LightGraphs

import QuantumWalk: check_qwdynamics, evolve, measure, QWEvolution
##

abstract type AbstractStochastic <: QWModelDiscr end

struct UniformStochastic{G<:SimpleGraph} <: AbstractStochastic
  graph::G
end

UniformScaling(digraph::G) where G= UniformStochastic{G}(digraph)

function check_qwdynamics(::Type{QWEvolution},
                          abs_stoch::UniformStochastic,
                          parameters::Dict{Symbol,Any})
  @assert :stochastic ∈ keys(parameters) "parameters needs to have key stochastic"
  n = nv(graph(abs_stoch))
  @assert isa(parameters[:stochastic], SparseMatrixCSC{<:Real}) "value for :stochastic needs to be sparse matrix with real numbers"
  @assert size(parameters[:stochastic], 1) == size(parameters[:stochastic], 2) "Stochastic matrix needs to be square stochastic matrix"
  @assert mapslices(sum, parameters[:stochastic], 1)[1,:] ≈ ones(n) "Stochastic matrix needs to be square stochastic matrix of order graph"
end

function stochastic_matrix(g::SimpleGraph)
  a = adjacency_matrix(g)
  a*spdiagm(mapslices(x->1/sum(x), a, 1)[1,:])
end

function QWEvolution(stoch::AbstractStochastic)
   parameters = Dict{Symbol,Any}(:stochastic => stochastic_matrix(graph(stoch)))
   QWEvolution(stoch, parameters)
end

function stochastic_evolution(s::SparseMatrixCSC{T}, v::Vector{T}) where T<:Real
  s*v
end

function evolve(qws::QWDynamics{<:AbstractStochastic}, state)
  stochastic_evolution(parameters(qws)[:stochastic], state)
end

function measure(::QWDynamics{<:AbstractStochastic}, state::Vector{<:Real})
   return state
end

function measure(::QWDynamics{<:AbstractStochastic},
                 state::Vector{<:Real},
                 vertices::Vector{Int})
   return state[vertices]
end

##

dynamic = QWEvolution(UniformStochastic(smallgraph(:bull)))

println(execute_single(dynamic, fill(1./5, 5), 5))


text:
using BinaryBuilder

sources = ["./src"]

# There are more supported platforms available in BinaryBuilder
# (see supported_platforms()), but just build the most common ones.
platforms = [
    Linux(:i686, :glibc),
    Linux(:x86_64, :glibc),
    Linux(:armv7l, :glibc),
    MacOS(:x86_64),
    FreeBSD(:x86_64),
    Windows(:i686),
    Windows(:x86_64)
]

# Libddierckx links to libgfortran, so we need to build specific to
# Libgfortran version (equivalently the gcc version)
platforms = expand_gcc_versions(platforms)

# some platforms don't work. :(
non_working_platforms = [
    MacOS(:x86_64, compiler_abi=CompilerABI(:gcc4))
]
platforms = setdiff(platforms, non_working_platforms)

script = raw"""
cd $WORKSPACE/srcdir/ddierckx

flags="-O3 -shared -fPIC"
libdir="lib"

# set suffix
if [[ ${target} == *-mingw32 ]]; then
    suffix="dll"
# flags="${flags} -static-libgfortran -static-libgcc"
    libdir="bin"
elif [[ ${target} == *apple* ]]; then
    suffix="dylib"
else
    suffix="so"
fi

mkdir -p $WORKSPACE/destdir/${libdir}
gfortran -o $WORKSPACE/destdir/${libdir}/libddierckx.${suffix} ${flags} *.f
"""

dependencies = []
products(prefix) = [LibraryProduct(prefix, "libddierckx", :libddierckx)]

build_tarballs(ARGS, "libddierckx", v"1.0.0", sources, script, platforms,
               products, dependencies)


text:
"""
    tfisingMPO(h, N[; T = ComplexF64])
returns a Z2-symmetric MPO for the transverse field Ising model:
```
    H = -∑_i σ^i_x σ^(i+1)_x - ∑_i h σ^i_z
```
on N sites.
"""
function tfisingMPO(h, N; T = ComplexF64)
    bulk = DASTensor{T,4}(
        Z2(),
        ntuple(i -> Z2Charges(),4),
        ([2,2], [1,1], [1,1], [2,2]),
        InOut(1,1,-1,-1))
    #this construction is dangerous insofar as we deliberately don't
    #populate certain sectors to avoid having to introduce more logic
    #for a more robust setting:
    #vd = 2
    #track whether operation happened or not

    preapp  = T[0 0; 0 1] # 1 -> 1
    postapp = T[1 0; 0 0] # 2 -> 2
    app     = T[0 0; 1 0] # 1 -> 2
    peye= Matrix{T}(I, 1, 1)

    for ch in Z2Charges()
        #transverse field term
        hz = ifelse(iszero(ch), h, -h)
        @tensor deg[1,2,3,4] := (preapp[1,4] + postapp[1,4] - hz*app[1,4]) * peye[2,3]
        bulk[DASSector(Z2Charge(0), ch, ch, Z2Charge(0))] = deg

        #XX term
        @tensor deg[1, 2, 3, 4] := -preapp[1, 4] * peye[2, 3]
        bulk[DASSector(Z2Charge(0), ch ⊕ Z2Charge(1), ch, Z2Charge(1))] = deg

        @tensor deg[1, 2, 3, 4] :=  app[1, 4] * peye[2, 3]
        bulk[DASSector(Z2Charge(1), ch, ch ⊕ Z2Charge(1), Z2Charge(0))] = deg
    end

    # (3)        (4)        (3)
    # [lb](2) (2)[b](3) (2)[rb]
    # (1)        (1)        (1)
    lb = DASTensor{T,1}(Z2(), (Z2Charges(),), ([2,2],), InOut(-1))
    rb = DASTensor{T,1}(Z2(), (Z2Charges(),), ([2,2],), InOut( 1))
    lb[DASSector(Z2Charge(0))] = [0, 1]
    rb[DASSector(Z2Charge(0))] = [1, 0]

    @tensor bulk[1,2,3,4]       := bulk[2,1,4,3]
    @tensor leftbound[1, 2, 3]  := lb[-1] *  bulk[1, -1, 2, 3]
    @tensor rightbound[1, 2, 3] := bulk[1, 2, -1, 3] * rb[-1]

    return MPO{N}(leftbound, bulk,  rightbound)
end

"""
    sigmaZop([T = ComplexF64])
return the Z2-symmetric σz operator.
"""
function sigmaZop(T = ComplexF64)
    a = DASTensor{T,2}(Z2(),
        (Z2Charges(), Z2Charges()),
        ([1,1],[1,1]),
        InOut(1,-1))
    for ch in Z2Charges()
        a[DASSector(ch, ch)] = reshape([ifelse(iszero(ch), 1, -1)],1,1)
    end
    return a
end


text:
module TDA

using ComputationalHomology
using RecipesBase

include("pdiag.jl")

end


text:
using NewtonsMethod
using Test

@testset "NewtonsMethod.jl" begin
    atol = 1e-4
    f1(x) = 2x+1
    g1(x) = 2
    f2(x) = (x-1)^2
    g2(x) = 2(x-1)
    f3(x) = exp(x)-1
    g3(x) = exp(x)
    f4(x) = 2 + x^2
    g4(x) = 2x

    # Tests for known functions - analytical derivatives
    @test isapprox(newtonroot(f1, g1; x₀ = 10.0).value, -0.5, atol=atol)
    @test isapprox(newtonroot(f2, g2; x₀ = 10.0).value, 1.0, atol=atol)
    @test isapprox(newtonroot(f3, g3; x₀ = 10.0).value, 0.0, atol=atol)

    # Tests for known functions - automatic derivatives
    @test isapprox(newtonroot(f1; x₀ = 10.0).value, -0.5, atol=atol)
    @test isapprox(newtonroot(f2; x₀ = 10.0).value, 1.0, atol=atol)
    @test isapprox(newtonroot(f3; x₀ = 10.0).value, 0.0, atol=atol)

    # Tests using BigFloat
    @test isapprox(newtonroot(f1, g1; x₀ = BigFloat(10.0)).value, -0.5, atol=atol)
    @test isapprox(newtonroot(f2, g2; x₀ = BigFloat(10.0)).value, 1.0, atol=atol)
    @test isapprox(newtonroot(f3, g3; x₀ = BigFloat(10.0)).value, 0.0, atol=atol)
    @test isapprox(newtonroot(f1; x₀ = BigFloat(10.0)).value, -0.5, atol=atol)
    @test isapprox(newtonroot(f2; x₀ = BigFloat(10.0)).value, 1.0, atol=atol)
    @test isapprox(newtonroot(f3; x₀ = BigFloat(10.0)).value, 0.0, atol=atol)

    # Tests for non-convergence handling
    @test isnothing(newtonroot(f4, g4; x₀ = 10.0).value)
    @test isnothing(newtonroot(f4; x₀ = 10.0).value)

    # Tests that maxiter is working
    @test newtonroot(f4, g4; x₀ = 10.0, maxiter = 5).iter == 6
    @test newtonroot(f4; x₀ = 10.0, maxiter = 5).iter == 6

    # Tests that tol is working
    @test abs(newtonroot(f2, g2; x₀ = 10.0, tol = 1e-1).value - 1.0) >
          abs(newtonroot(f2, g2; x₀ = 10.0, tol = 1e-10).value - 1.0)
    @test abs(newtonroot(f2; x₀ = 10.0, tol = 1e-1).value - 1.0) >
          abs(newtonroot(f2; x₀ = 10.0, tol = 1e-10).value - 1.0)
    @test abs(newtonroot(f3, g3; x₀ = 10.0, tol = 1e-1).value) >
          abs(newtonroot(f3, g3; x₀ = 10.0, tol = 1e-10).value)
    @test abs(newtonroot(f3; x₀ = 10.0, tol = 1e-1).value) >
          abs(newtonroot(f3; x₀ = 10.0, tol = 1e-10).value)
end


text:
"""
    gencorrresult(fd_range, Δfd, sample_num; iszeros=false)

Generates a 2D `Array{Float64,2}` to store the cross correlation results output
from the `courseacquisition` function.

Required Arguments:

- `fd_range::Float64`: the range of Doppler plus minus the center frequency in Hz
- `Δfd::Float64`: frequency bin width in Hz

Optional Arguments:

- `iszeros::Bool`: if `true`, sets contents of array to zero, otherwise its
                   elements are set to `undef` `(default = false)`

Returns:

- `Array{Float64,2}`: 2D array to store acquistion result
"""
function gencorrresult(fd_range, Δfd, sample_num; iszeros=false)
    doppler_bin_num = round(Int, 2*fd_range/Δfd+1)
    if iszeros
        # Initialize with zeros
        return zeros(Float64, doppler_bin_num, sample_num)
    else
        # Allocate space, but don't initialize elements to a value
       return Array{Float64}(undef, doppler_bin_num, sample_num)
    end
end

"""
    courseacquisition(data::GNSSSignal, replica::ReplicaSignal,
                      prn; fd_center=0., fd_range=5000., M=1,
                      fd_rate=0., Δfd=1/(1*replica.t_length),
                      start_idx=1, return_corrresult=false,
                      p_fa=1e-7)

Performs course acquisition using an integration time specified by
`replica.t_length`, and adds `M` coherent integrations non-coherently.

Required Arguments:

- `data::GNSSSignal`: either a `GNSSData` or `ReplicaSignal`
    * can be either simulated or real data
- `replica::ReplicaSignal`: replica signal whose length determines the
                             integration time used for course acquisition
- `prn::Int`: PRN number refering to code to search for

Optional Arguments:

- `fd_center::Float64`: center Doppler frequency bin value in Hz `(default = 0Hz)`
- `fd_range::Float64`: the range of Doppler frequencies in Hz to search plus and
                       minus the center Doppler frequency bin `(default = 5000Hz)`
- `M::Int`: the number of coherent integrations to add together. This is
            non-coherent integration `(default = 1)`
- `fd_rate::Float64`: the Doppler frequency rate in Hz/s `(default = 0Hz)`
- `Δfd::Float64`: the Doppler bin width in Hz `(default = 1/replica.t_length)`
    * usually determined by the length of the integration time
    * integration time is determined by the length of the replica
      `replica.t_length`
- `start_idx::Int`: starting sample in data plus `replica.sample_num` that is
                    used for processing `(default = 1)`
- `return_corrresult::Bool`: set to `true` to return the 2D correlation result
                             `(default = true)`
- `p_fa`: probability of false alarm `(default = 1e-7)`

Returns:

- `fd_est::Float64`: Doppler frequency bin corresponding to peak in Hz
- `n0_est::Int`: index in data where code starts
- `SNR_est::Float64`: SNR of the correlation peak in dB
- `corr_result::Array{Float64,2}`: (optional) 2D array to store acquistion result
"""
function courseacquisition(data::GNSSSignal, replica::ReplicaSignal,
                           prn; fd_center=0., fd_range=5000., M=1,
                           fd_rate=0., Δfd=1/(1*replica.t_length),
                           start_idx=1, return_corrresult=false,
                           p_fa=1e-7)
    # Perform coherent intefration where the integration time is decided based
    # off the length of `replica.t_length`
    if M == 1
        # Allocate space for correlation result
        corr_result = gencorrresult(fd_range, Δfd, replica.sample_num)
        # Perform course acquisition
        courseacquisition!(corr_result, data, replica, prn;
                           fd_center=fd_center, fd_range=fd_range,
                           fd_rate=fd_rate, Δfd=Δfd, start_idx=start_idx,
                           operation="replace")
    # Perform non-coherent integration where the integration time is based off
    # `replica.t_length` and `M` coherent integrations are added together
    else
        @assert M > 1
        # Allocate space for correlation result
        corr_result = gencorrresult(fd_range, Δfd, replica.sample_num,
                                    iszeros=true)
        # Perform course acquisition
        for i in 1:M
            idx = start_idx + (i-1)*replica.sample_num
            # replica.t .+= (i > 1)*replica.t_length
            replica.start_t += (i > 1)*replica.t_length
            courseacquisition!(corr_result, data, replica, prn;
                               fd_center=fd_center, fd_range=fd_range,
                               fd_rate=fd_rate, Δfd=Δfd, start_idx=idx,
                               operation="add")
        end
        replica.start_t = 0
    end
    # Get the code offset in samples, course Doppler, and peak SNR in dB
    n0_est, fd_est, SNR_est,
    P_d, above_threshold = course_acq_est(corr_result, fd_center, fd_range,
                                          Δfd; p_fa=p_fa, M=M)
    if return_corrresult
        return (fd_est, n0_est, SNR_est, P_d, above_threshold, corr_result)
    else
        return (fd_est, n0_est, SNR_est, P_d, above_threshold)
    end
end

"""
    courseacquisition!(corr_result::Array{Float64,2},
                       data::GNSSSignal, replica::ReplicaSignal,
                       prn; fd_center=0., fd_range=5000.,
                       fd_rate=0., Δfd=1/replica.t_length,
                       operation="replace", start_idx=1)

Performs course acquisition on either `GNSSData` or `ReplicaSignal`
type struct using defined `ReplicaSignal` type struct. No need
to use `generatereplica!` before calling this function.
Operates in place on `corr_result`.

*NOTE:* If `data` is a replica signal structure type,
        it's structure type must be the same as the type
        of `replica`. They must also be separately defined
        or one must be a deep copy of the other. Do not
        pass the same structure to the `data` and `replica`
        arguments.

`corr_result` contains |conj(fft(replica)*fft(data)|² per
Doppler bin.

Required Arguments:

- `corr_result::Array{Float64,2}`: 2D array to store acquistion result
- `data::GNSSSignal`: either a `GNSSData` or `ReplicaSignal`
    * can be either simulated or real data
- `replica::ReplicaSignal`: replica signal whose length determines the
                             integration time used for course acquisition
- `prn::Int`: PRN number refering to code to search for

Optional Arguments:

- `fd_center::Float64`: center Doppler frequency bin value in Hz `(default = 0Hz)`
- `fd_range::Float64`: the range of Doppler frequencies in Hz to search plus and
                       minus the center Doppler frequency bin `(default = 5000Hz)`
- `fd_rate::Float64`: the Doppler frequency rate in Hz/s `(default = 0Hz)`
- `Δfd::Float64`: the Doppler bin width in Hz `(default = 1/replica.t_length)`
    * usually determined by the length of the integration time
    * integration time is determined by the length of the replica
      `replica.t_length`
- `start_idx::Int`: starting sample in data plus `replica.sample_num` that is
                    used for processing `(default = 1)`

Modifies and Returns:

- `corr_result::Array{Float64,2}`: 2D array to store acquistion result
"""
function courseacquisition!(corr_result::Array{Float64,2},
                            data::GNSSSignal, replica::ReplicaSignal,
                            prn; fd_center=0., fd_range=5000.,
                            fd_rate=0., Δfd=1/replica.t_length,
                            operation="replace", start_idx=1)
    # Number of data samples
    dsize = replica.sample_num
    # Pre-plan FFTs and IFFTs
    pfft = plan_fft!(replica.data)  # In-place FFT plan
    pifft = plan_ifft!(replica.data) # In-place IFFT plan
    # Carrier wipe data signal, make copy, and take FFT
    datafft = Array{Complex{Float64}}(undef, dsize)
    j = 1
    for i in start_idx:(start_idx+dsize-1)
        t = calc_t_at_i(i, replica.start_t, replica.f_s)
        datafft[j] = data.data[i] * exp(-2π*data.f_if*t*1im)
        j += 1
    end
    # In-place FFT
    pfft*datafft
    # Number of bits representing `data`
    nADC = data.nADC
    # Number of Doppler bins
    doppler_bin_num = floor(Int, 2*fd_range/Δfd+1)
    @inbounds for i in 1:doppler_bin_num
        # Calculate Doppler frequency for `i` Doppler bin
        f_d = (fd_center-fd_range) + (i-1)*Δfd
        # Set signal parameters
        definereplica!(replica;
                       prn=prn, f_d=f_d,
                       fd_rate=fd_rate, phi=0., f_if=0.,
                       code_start_idx=1,
                       include_carrier=true)
        # Generate signal
        generatereplica!(replica)
        # Perform in place FFT on replica
        pfft*replica.data
        # Take conjugate of FFT(replica) and multiply with FFT of
        # data. The result is stored in `replica.data`
        conjAmultB1D!(replica.data, datafft, dsize)
        # Take IFFT in place
        pifft*replica.data
        # Take `abs2` in place and save result
        # Either replace, add to, or multiply by pre-existing value
        # in `corr_result`
        # for j in 1:dsize
        @threads for j in 1:dsize
            if operation == "replace"
                @inbounds corr_result[i,j] = abs2(replica.data[j])
            elseif operation == "add"
                @inbounds corr_result[i,j] += abs2(replica.data[j])
            elseif operation == "multiply"
                @inbounds corr_result[i,j] *= abs2(replica.data[j])
            end
        end
    end
    # corr_result[:,:] .= corr_result[:,:].^2
    # Set `isreplica` flag to false in `replica`
    definesignal!(replica, isreplica=false)
    return corr_result
end

"""
    course_acq_est(corr_result)

Estimate the code start index, Doppler frequency and peak SNR from the
correlation result.

Required Arguments:

- `corr_result::Array{Float64,2}`: 2D array that contains course acquistion
                                   result

Returns:

- `n0_est::Int`: index in data where code starts
- `fd_est::Float64`: Doppler frequency bin corresponding to peak in Hz
- `SNR_est::Float64`: SNR of the peak in dB
"""
function course_acq_est(corr_result, fd_center, fd_range, Δfd;
                        p_fa=1e-7, M=1)
    # Get peak maximum index location
    max_idx = argmax(corr_result)
    # Calculate course Doppler frequency
    fd_est = (fd_center-fd_range) + (max_idx[1]-1)*Δfd
    # Get course peak index location in time
    n0_est = max_idx[2]
    pk_val = corr_result[max_idx]
    # Compute course acquisition SNR
    PS = pk_val
    rows, cols = size(corr_result)
    noise_row_idx = (max_idx[1] + 2) % rows + 1
    noise_val = std(corr_result[noise_row_idx,:])
    # noise_val = sum(corr_result[noise_row_idx,:])
    # noise_val = sum(corr_result)
    # PN = (noise_val - pk_val)/(rows*cols - 1)
    # PN = noise_val/(cols - 1)
    PN = noise_val
    SNR_est = calc_snr(PS, PN)
    v_i = sqrt(PS)
    σ = sqrt(PN)
    v_t = p_fa2v_t(p_fa, σ)
    P_d = v_t2p_d(v_t, σ, v_i=v_i)
    if v_i >= v_t
        above_threshold = true
    else
        above_threshold = false
    end
    return (n0_est, fd_est, SNR_est, P_d, above_threshold)
end

"""
    v_t2p_fa(v_t, σ_n)

Calculate the probability of false alarm based off the threshold and noise
standard deviation.

Required Arguments:

- `v_t`: the threshold set for acquisition
- `σ_n`: the standard deviation of the noise

Returns:

- `p_fa`: the probability of false alarm
"""
function v_t2p_fa(v_t, σ_n)
    return exp(-v_t^2 / (2*σ_n^2))
end

"""
    p_fa2v_t(p_fa, σ_n)

Calculate the threshold value for acquisition based off the probability of
false alarm and the noise standard deviation.

Required Arguments:

- `p_fa`: the probability of false alarm between 0 and 1
- `σ_n`: the standard deviation of the noise

Returns:

- `v_t`: the threshold for acquisition
"""
function p_fa2v_t(p_fa, σ_n)
    return sqrt(2*σ_n^2*log(1/p_fa))
end

"""
    false_alarm_pdf(v, σ_n)

Calculate the value of the false alarm PDF at a given value, `v`, with
noise standard deviation, `σ_n`.

Required Arguments:

- `v`: value to evaluate PDF at
- `σ_n`: standard deviation of the noise

Returns:

- PDF value at `v`
"""
function false_alarm_pdf(v, σ_n)
    return v*exp(-v^2/σ_n)/σ_n^2
end

"""
    I₀(x)

Evaluates the Modified Bessel function of the 1st kind order zero.

Arguments:

- `x`: where to evaluate I₀ at

Returns:

- I₀(x)
"""
function I₀(x)
    return quadgk(θ -> exp(big(x)*cos(big(θ))), 0, π)[1]/π
end

"""
    detection_pdf(v, σ_n; SNR=missing, v_i=missing)

Calculate the value of the detection PDF at a given value, `v`, with
noise standard deviation, `σ_n`, and `SNR`.

Required Arguments:

- `v`: value to evaluate PDF at
- `σ_n`: standard deviation of the noise
- `SNR`: desired signal-to-noise ratio in dB '(default = missing)` or
- 'v_i': the amplitude of the signature in place of the `SNR` '(default = missing)`

Returns:

- PDF value at `v`
"""
function detection_pdf(v, σ_n; SNR=missing, v_i=missing)
    if ismissing(SNR) && !ismissing(v_i)
        x = v*v_i/σ_n^2
        return (v/σ_n^2)*exp(-(v^2 + v_i^2)/(2*σ_n^2))*I₀(x)
    elseif !ismissing(SNR) && ismissing(v_i)
        SNR_linear = 10^(SNR/10)
        x = (v/σ_n)*sqrt(2*SNR_linear)
        return (v/σ_n^2)*exp(-(v^2/(2*σ_n^2) + SNR_linear))*I₀(x)
    else
        error("Must provide either `SNR` or `v_i`, not both or none.")
    end
end

"""
    v_t2p_d(v_t, σ_n, SNR; rtol=1e-3, order=3, std_scalar=20,
            steps=missing)

Calculates the probability of detection based off a threshold value, `v_t`,
noise standard deviation, `σ_n`, and desired `SNR`.

Required Arguments:

- `v_t`: threshold value used for acquisition
- `σ_n`: standard deviation of the noise
- `SNR`: desired signal-to-noise ratio in dB '(default = missing)` or
- `v_i`: the amplitude of the signature in place of the `SNR` '(default = missing)`

Optional Arguments:

- `rtol`: tolerance for numerical integration `(default = 1e-3)`
- `order`: order of the numerical integration `(default = 3)`

Returns:

- probability of detection, `P_d`
"""
function v_t2p_d(v_t, σ_n; SNR=missing, v_i=missing,
                 rtol=1e-10, order=7)
    v_t = big(v_t)
    σ_n = big(σ_n)
    if !ismissing(SNR) && ismissing(v_i)
        SNR = big(SNR)
    elseif ismissing(SNR) && !ismissing(v_i)
        v_i = big(v_i)
    else
        error("Must provide either SNR or v_i.")
    end
    p_d_pdf(v) = detection_pdf(v, σ_n; SNR=SNR, v_i=v_i)
    return quadgk(p_d_pdf, v_t, Inf, rtol=rtol, order=order)[1]
end

"""
    p_d2v_t(p_d, σ_n, SNR)

Calculates the threshold value, `v_t`, based off the probability of detection,
`p_d`, the noise standard deviation, `σ_n`, and the desired `SNR`.

Required Arguments:

- `p_d`: probability of detection between 0 and 1
- `σ_n`: standard deviation of the noise
- `SNR`: desired signal-to-noise ratio in dB

Optional Arguments:

- `rtol`: tolerance for numerical integration `(default = 1e-3)`
- `order`: order of the numerical integration `(default = 3)`

Returns:

- threshold value, `v_t`
"""
function p_d2v_t(p_d, σ_n, SNR; rtol=1e-10, order=7)
    SNR_linear = 10^(SNR/10)
    p_d_pdf(v) = detection_pdf(v, σ_n; SNR=SNR_linear)
    Pd(v) = quadgk(p_d_pdf, v[1], Inf, rtol=rtol, order=order)[1]
    δp_d(v) = abs(Pd(v) - p_d)
    result = optimize(δp_d, [0.], [1000], [0.])
    return result
end

"""
    noncoherent_loss(M, p_fa, p_d)

Calculates the noncoherent integration loss.

Required Arguments:

- `M`: the number of noncoherent integrations, each with length `T` seconds
- `p_fa`: the probability of false alarm
- `p_d`: the probability of detection

Returns:

- `L(M)`: the noncoherent integration loss in dB
"""
function noncoherent_loss(M, p_fa, p_d)
    Dc = (erfinv(1 - 2*p_fa) - erfinv(1 - 2*p_d))^2
    return 10log10((1 + sqrt(1 + 9.2*M/Dc)) / (1 + sqrt(1 + 9.2/Dc)))
end

"""
    processing_gain(T, M=1; p_fa=1e-7, p_d=0.9)

Calculates the expected processing gain for `M` noncoherent integrations of
length `T` seconds.

Required Arguments:

- `T`: the integration time in seconds

Optional Arguments:

- `M`: the number of noncoherent integrations, each with length `T` `(default=1)`
- `p_fa`: the probability of false alarm `(default=1e-7)`
- `p_d`: the probability of detection `(default=0.9)`

Returns:

- `G_coherent + G_noncoherent`: the coherent plus the noncoherent processing
  gains in dB
"""
function processing_gain(T, M=1; p_fa=1e-7, p_d=0.9)
    G_coherent = 10log10(T)
    G_noncoherent = 10log10(M) - noncoherent_loss(M, p_fa, p_d)
    return G_coherent + G_noncoherent
end


text:
module VLQ

include("evaluate_qec.jl")
include("fast_syndrome.jl")
include("noise_model.jl")

end

max_stars_repo_name: yongshanding/VLQ

max_issues_repo_name: yongshanding/VLQ

max_forks_repo_name: yongshanding/VLQ


text:
HEIGHT=400
WIDHT=400
BACKGROUND= colorant"purple"
alien_actor=Actor("alien.png")
alien_actor.pos= (120,180)
text_actor=TextActor("hello boys","moonhouse")

text_actor.pos=(120,120)
rect=Rect(50,100,20,50)
cir = Circle(330,80,20)

i=0
function draw()
    draw(alien_actor)
    draw(text_actor)
    draw( Line(50+i,100,350+i,100),colorant"yellow")
    draw(rect,colorant"white",fill=true)
    draw(cir,colorant"black",fill=true)
end

function update()
    alien_actor.x=alien_actor.x+2
    alien_actor.y+=1
    text_actor.y+=1
    global i
    i+=10
end

max_stars_repo_name: stepinski/julia-in

max_issues_repo_name: stepinski/julia-init

max_forks_repo_name: stepinski/julia-init


text:
mutable struct MemoryBuffer{L,T} <: DenseVector{T}
    data::NTuple{L,T}
    @inline function MemoryBuffer{L,T}(::UndefInitializer) where {L,T}
        @assert isbitstype(T) "Memory buffers must point to bits types, but `isbitstype($T) == false`."
        new{L,T}()
    end
end

@inline undef_memory_buffer(::Type{T}, ::StaticInt{L}) where {T,L} = MemoryBuffer{L,T}(undef)
@inline undef_memory_buffer(::Type{T}, L) where {T} = Vector{T}(undef, L)

struct StrideArray{S,D,T,N,C,B,R,X,O,A} <: AbstractStrideArray{S,D,T,N,C,B,R,X,O}
    ptr::PtrArray{S,D,T,N,C,B,R,X,O}
    data::A
end

@inline VectorizationBase.stridedpointer(A::StrideArray) = A.ptr.ptr

const StrideVector{S,D,T,C,B,R,X,O,A} = StrideArray{S,D,T,1,C,B,R,X,O,A}
const StrideMatrix{S,D,T,C,B,R,X,O,A} = StrideArray{S,D,T,2,C,B,R,X,O,A}

@inline StrideArray(A::AbstractArray) = StrideArray(PtrArray(A), A)

@inline VectorizationBase.preserve_buffer(A::MemoryBuffer) = A
@inline VectorizationBase.preserve_buffer(A::StrideArray) = preserve_buffer(A.data)

@inline maybe_ptr_array(A) = A
@inline maybe_ptr_array(A::AbstractArray) = maybe_ptr_array(ArrayInterface.device(A), A)
@inline maybe_ptr_array(::ArrayInterface.CPUPointer, A::AbstractArray) = PtrArray(A)
@inline maybe_ptr_array(_, A::AbstractArray) = A

@inline ArrayInterface.size(A::StrideArray) = getfield(getfield(A, :ptr), :size)

@inline VectorizationBase.bytestrides(A::StrideArray) = getfield(getfield(getfield(A, :ptr), :ptr), :strd)
@inline ArrayInterface.strides(A::StrideArray) = strides(getfield(A, :ptr))
@inline ArrayInterface.offsets(A::StrideArray) = getfield(getfield(getfield(A, :ptr), :ptr), :offsets)

@inline zeroindex(r::ArrayInterface.OptionallyStaticUnitRange{One}) = CloseOpen(Zero(), last(r))
@inline zeroindex(r::Base.OneTo) = CloseOpen(Zero(), last(r))
@inline zeroindex(r::AbstractUnitRange) = Zero():(last(r)-first(r))

@inline zeroindex(r::CloseOpen{Zero}) = r
@inline zeroindex(r::ArrayInterface.OptionallyStaticUnitRange{Zero}) = r

function gc_preserve_call(ex, skip=0)
    q = Expr(:block)
    call = Expr(:call, esc(ex.args[1]))
    gcp = Expr(:gc_preserve, call)
    for i ∈ 2:length(ex.args)
        arg = ex.args[i]
        if i+1 ≤ skip
            push!(call.args, arg)
            continue
        end
        A = gensym(:A); buffer = gensym(:buffer);
        if arg isa Expr && arg.head === :kw
            push!(call.args, Expr(:kw, arg.args[1], Expr(:call, :maybe_ptr_array, A)))
            arg = arg.args[2]
        else
            push!(call.args, Expr(:call, :maybe_ptr_array, A))
        end
        push!(q.args, :($A = $(esc(arg))))
        push!(q.args, Expr(:(=), buffer, Expr(:call, :preserve_buffer, A)))
        push!(gcp.args, buffer)
    end
    push!(q.args, gcp)
    q
end
"""
  @gc_preserve foo(A, B, C)

Apply to a single, non-nested, function call. It will `GC.@preserve` all the arguments, and substitute suitable arrays with `PtrArray`s.
This has the benefit of potentially allowing statically sized mutable arrays to be both stack allocated, and passed through a non-inlined function boundary.
"""
macro gc_preserve(ex)
    @assert ex.head === :call
    gc_preserve_call(ex)
end


text:
NumTestRepetitions = 100

facts("Adaptive differential evolution optimizer") do

ade = adaptive_de_rand_1_bin()

context("sample_f") do
  for(i in 1:NumTestRepetitions)
    @fact 0.0 <= BlackBoxOptim.sample_f(ade) <= 1.0 => true
  end
end

context("ask") do
  for(i in 1:NumTestRepetitions)
    res = BlackBoxOptim.ask(ade)

    @fact length(res) => 2
    trial, trialIndex = res[1]
    target, targetIndex = res[2]

    @fact ndims(trial) => 2
    @fact 1 <= trialIndex <= length(ade.population) => true
    @fact isinspace(trial, ade.search_space) => true

    @fact ndims(target) => 2
    @fact 1 <= targetIndex <= length(ade.population) => true
    @fact isinspace(target, ade.search_space) => true

    @fact trialIndex == targetIndex => true
  end
end

end


text:
function errorCheck(a1,a2,p)
    if length(a1)!= length(a2)
        println("The arrays have different length")
        return -1
        end
        if p<1
            println("the value attributed to 'p' must be at least 1")
            return -1
        end
    return 0
end

function euclidianDistance(a1,a2)
        if errorCheck(a1,a2,1) !=-1
                return sqrt((sum((a1-a2).^2)))
        end
end

function manhattanDistance(a1,a2)
        if errorCheck(a1,a2,1) !=-1
                return sum(abs.((a1-a2)))
        end
end

function cosineDistance(a1,a2)
        if errorCheck(a1,a2,1) !=-1
                return 1 - sum(a1.*a2)/(sqrt(sum(a1.^2))*sqrt(sum(a2.^2)))
        end
end

function minkowskiDistance(a1,a2,p)
        if errorCheck(a1,a2,p) !=-1
                return (sum(abs.(a1-a2).^p))^1/p
        end
end

function jaccardSimilarity(a1,a2)
        if errorCheck(a1,a2,1) !=-1
                return length(intersect(a1,a2))/length(union(a1,a2))
        end
end

function jaccardDistance(a1,a2)
        if errorCheck(a1,a2,1) !=-1
                return 1 - jaccardSimilarity(a1,a2)
        end
end

max_stars_repo_name: nicolasmagalhaes/DistanceAndSimilarity

max_issues_repo_name: nicolasmagalhaes/DistanceAndSimilarity

max_forks_repo_name: nicolasmagalhaes/DistanceAndSimilarity


text:
######################################################################

struct FAbs2{T<:AbstractFunctionWithParameters} <: AbstractFunctionWithParameters
    f::T
end
func(d::FAbs2, x::NumberOrTuple; p=freepars(d)) = abs2(func(d.f,x;p))
pars(d::FAbs2, isfree::Bool) = pars(d.f, isfree)
updatevalueorflag(d::FAbs2, s::Symbol, isfree::Bool, v=getproperty(pars(d),s)) =
    FAbs2(updatevalueorflag(d.f,s,isfree,v))
#
abs2(f::AbstractFunctionWithParameters) = FAbs2(f)

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

struct FLog{T<:AbstractFunctionWithParameters} <: AbstractFunctionWithParameters
    f::T
end
func(d::FLog, x::NumberOrTuple; p=freepars(d)) = log(func(d.f,x;p))
pars(d::FLog, isfree::Bool) = pars(d.f, isfree)
updatevalueorflag(d::FLog, s::Symbol, isfree::Bool, v=getproperty(pars(d),s)) =
    FLog(updatevalueorflag(d.f,s,isfree,v))
#
log(f::AbstractFunctionWithParameters) = FLog(f)

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

struct FProd{
        T1<:AbstractFunctionWithParameters,
        T2<:AbstractFunctionWithParameters} <: AbstractFunctionWithParameters
    f1::T1
    f2::T2
end
func(d::FProd, x::NumberOrTuple; p=freepars(d)) = func(d.f1,x;p) * func(d.f2,x;p)
pars(d::FProd, isfree::Bool) = pars(d.f1, isfree) + pars(d.f2, isfree)
updatevalueorflag(d::FProd, s::Symbol, isfree::Bool, v=getproperty(pars(d),s)) =
    FProd(
        ispar(d.f1,s) ? updatevalueorflag(d.f1,s,isfree,v) : d.f1,
        ispar(d.f2,s) ? updatevalueorflag(d.f2,s,isfree,v) : d.f2)
#
*(f1::AbstractFunctionWithParameters, f2::AbstractFunctionWithParameters) = FProd(f1,f2)

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

struct FSum{T<:AbstractFunctionWithParameters,N,V}  <: AbstractFunctionWithParameters
    fs::StaticVector{N,T}
    αs::V
end
function FSum(fs::Union{Tuple,AbstractVector}, αs)
    N = length(fs)
    FSum(SVector{N}(collect(fs)), αs)
end
#
length(d::FSum{T,N}) where {T,N} = N
pars(d::FSum, isfree::Bool) = sum(pars.(d.fs, isfree)) + pars(d.αs, isfree)
function getindex(d::FSum, i::Number)
    α_sym = keys(d.αs)[i]
    α_val = getproperty(d.αs, α_sym)
    FSum([d.fs[i]], nt(α_sym, α_val))
end
const FSumFunc = AlgebraPDF.FSum{T} where T<:AbstractFunctionWithParameters
const FSumPDF = AlgebraPDF.FSum{T} where T<:AbstractPDF

function func(d::FSumFunc, x::NumberOrTuple; p=freepars(d))
    allp = p+fixedpars(d)
    α_vals = (getproperty(allp,s) for s in keys(d.αs))
    f_vals = func.(d.fs, Ref(x);p)
    return sum(α_vals .* f_vals)
end

#
function func_norm(d::FSumPDF, x; p=freepars(d)) # suppose to work also for all x <: AbstractVector
    allp = p+fixedpars(d)
    α_vals = (getproperty(allp,s) for s in keys(d.αs))
    f_vals = [f(x;p) for f in d.fs]
    return sum(α_vals .* f_vals)
end
func(d::FSumPDF, x::NumberOrTuple; p=freepars(d)) = func_norm(d,x;p)
func(d::FSumPDF, x::AbstractArray; p=freepars(d)) = func_norm(d,x;p)
func(d::FSumPDF, x::AbstractRange; p=freepars(d)) = func_norm(d,x;p)
lims(d::FSumPDF) = lims(d.fs[1])

function updatevalueorflag(d::FSum, s::Symbol, isfree::Bool, v=getproperty(pars(d),s))
    fs = [ispar(f,s) ? updatevalueorflag(f,s,isfree,v) : f for f in d.fs]
    αs = ispar(d.αs,s) ? updatevalueorflag(d.αs,s,isfree,v) : d.αs
    FSum(fs, αs)
end
#
function integral(d::FSumPDF; p=freepars(d.αs))
    allp = p+fixedpars(d.αs)
    sum(getproperty(allp,s) for s in keys(d.αs))
end

function integral(d::FSumPDF, lims; p=freepars(d))
    allp = p+fixedpars(d)
    α_vals = (getproperty(allp,s) for s in keys(d.αs))
    f_vals = integral.(d.fs, Ref(lims); p)
    return sum(α_vals .* f_vals)
end

+(f1::AbstractFunctionWithParameters,
  f2::AbstractFunctionWithParameters; p=(α1=1.0, α2=1.0)) = FSum([f1,f2], p)

-(f1::AbstractFunctionWithParameters,
  f2::AbstractFunctionWithParameters; p=(α1=1.0, α2=-1.0)) = FSum([f1,f2], p)

+(f1::FSum, f2::FSum) = FSum([f1.fs...,f2.fs...], f1.αs+f2.αs)

*(f::AbstractFunctionWithParameters, c::ParTypes) = FSum([f], c)
*(c::ParTypes, f::AbstractFunctionWithParameters) = FSum([f], c)

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

struct NegativeLogLikelihood{T<:AbstractFunctionWithParameters, D<:AbstractArray} <: AbstractFunctionWithParameters
    f::T
    data::D
    nagativepenatly::Float64
end
func(d::NegativeLogLikelihood, x::NumberOrTuple; p=freepars(d)) = -sum((v>0) ? log(v) : d.nagativepenatly for v in d.f(d.data;p))
pars(d::NegativeLogLikelihood, isfree::Bool) = pars(d.f, isfree)
updatevalueorflag(d::NegativeLogLikelihood, s::Symbol, isfree::Bool, v=getproperty(pars(d),s)) =
    NegativeLogLikelihood(updatevalueorflag(d.f,s,isfree,v), d.data, d.nagativepenatly)
#
NegativeLogLikelihood(d, data::AbstractArray) = NegativeLogLikelihood(d, data, -1e4)
minussum(d::FLog, data::AbstractArray) = NegativeLogLikelihood(d.f, data)

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

struct Extended{T <: AlgebraPDF.FSumPDF} <: AbstractFunctionWithParameters
    nll::NegativeLogLikelihood{T}
end

pars(d::Extended, isfree::Bool) = pars(d.nll, isfree)
updatevalueorflag(d::Extended, s::Symbol, isfree::Bool, v=getproperty(pars(d),s)) =
    Extended(updatevalueorflag(d.nll,s,isfree,v))
#
function func(d::Extended, x::NumberOrTuple; p=freepars(d))
    nll = func(d.nll, x; p)
    μ = integral(d.nll.f; p)
    penalty = μ
    return nll + penalty
end

# model property
model(nll::NegativeLogLikelihood) = nll.f
model(enll::Extended) = model(enll.nll)


text:
## Various possible plot interfaces

## Plot interfaces for functions

## plot(x, [y], args..., kwargs...) lineplot
## plot(x::Tuple{Vector}, args...; symboltype::AbstractString="o", kwargs...) scatter plot
## plot(fs::Tuple{Function}, a, b; kwargs) parametric plot
## plot(fs::Array{Function, 2}, a::Real, b::Real, args...; kwargs...) table of plots

const ScatterPlotPoints{T<:Real, S<:Real} = Tuple{Vector{T}, Vector{S}}

## plot a scatterplot (verbose alternative to plot(x, y, "o")
## use named argument symbol to pass in symbol -- not args)
function plot(p::FramedPlot, x::ScatterPlotPoints, args...; symbol="o", kwargs...)
    Base.warn_once("deprecated -- call scatter instead")
    plot(p, x[1], x[2], symbol, args...;  kwargs...)
end

errs_to_nan(f) = (x) -> try f(x) catch e NaN end

## parametric plot
const ParametricFunctionPair = Tuple{Function, Function}
function plot(p::FramedPlot, fs::ParametricFunctionPair, a::Real, b::Real, args...; npoints::Int=500, kwargs...)
    us = range(a, stop=b, length=npoints)
    xs = map(errs_to_nan(fs[1]), us)
    ys = map(errs_to_nan(fs[2]), us)
    plot(p, xs, ys, args...; kwargs...)
end

## Array
## kwargs are vectorized (without recycling)
## e.g.:  plot([sin cos]', 0, 2pi, color=["blue" "red"]')
function plot(fs::Array{Function, 2}, a::Real, b::Real, args...; kwargs...)
    m,n = size(fs)
    tbl = Table(m, n)
    for i in 1:m, j in 1:n
        f = fs[i,j]
        kws = [(k, v[i,j]) for (k, v) in kwargs]
        p = plot(f, a, b, args...; kws...)
        tbl[i,j] = p
    end

    tbl
end


text:
using Tensors
using Test
using TimerOutputs
using LinearAlgebra
using Random
using Statistics: mean

macro testsection(str, block)
    return quote
        @timeit "$($(esc(str)))" begin
            @testset "$($(esc(str)))" begin
                $(esc(block))
            end
        end
    end
end

reset_timer!()

include("F64.jl")
include("test_misc.jl")
include("test_ops.jl")
include("test_ad.jl")

print_timer()
println()


text:
# New factor interface, something perhaps like this

export CalcFactor
export testFactorResidualBinary

# Also see #467 on API consolidation
# function (cf::CalcFactor{<:LinearRelative})(res::AbstractVector{<:Real}, z, xi, xj)
#   # cf.metadata.variablelist...
#   # cf.metadata.targetvariable
#   # cf.metadata.usercache
#   # generic on-manifold residual function
#   res .= distance(z, distance(xj, xi))
# end

"""
    $TYPEDEF

New generation user factor interface method for computing the residual values of factors.

Notes
- Under development and still experimental.  Expected to become default method in IIF v0.20.0
"""
struct CalcFactor{T <: FunctorInferenceType, M, P <: Tuple, X <: AbstractVector}
  # the interface compliant user object functor containing the data and logic
  factor::T
  # the metadata to be passed to the user residual function
  metadata::M
  # what is the sample (particle) id for which the residual is being calculated
  _sampleIdx::Int
  # legacy support when concerned with how many measurement tuple elements are used by user
  _measCount::Int
  # legacy suport for measurement sample values of old functor residual functions
  _legacyMeas::P
  # legacy support for variable values old functor residual functions
  _legacyParams::X
end

"""
    $SIGNATURES

Sample the factor stochastic model `N::Int` times and store the samples in the preallocated `ccw.measurement` container.

DevNotes
- Use in place operations where possible and remember `measurement` is a `::Tuple`.
- TODO only works on `.threadid()==1` at present, see #1094
"""
function sampleFactor(cf::CalcFactor{<:FunctorInferenceType},
                      N::Int=1  )
  #
  getSample(cf, N)
end

function Base.show(io::IO, x::CalcFactor)
  println(io, )
  printstyled(io, " CalcFactor:\n", color=:blue)
  println(io, "  .factor: ", typeof(x.factor))
end

Base.show(io::IO, ::MIME"text/plain", x::CalcFactor) = show(io, x)

"""
    $SIGNATURES

Evaluate the residual function for a single sample.

Notes
- Binary factors only at this stage, and `multihypo` does not have to be considered in this test

DevNotes
- TODO generalize for n-ary factors

Related

[`approxConv`](@ref), [`CalcResidual`](@ref)
"""
function testFactorResidualBinary(fct,
                                  T1,
                                  T2,
                                  param1,
                                  param2,
                                  meas::Tuple = ())
  #

  fg_ = initfg()
  X0 = addVariable!(fg_, :x0, T1)
  X1 = addVariable!(fg_, :x1, T2)
  addFactor!(fg_, [:x0;:x1], fct, graphinit=false)

  ccw = IIF._getCCW(fg_, :x0x1f1)

  ARR = getPoints.(getBelief.(fg_, [:x0;:x1]))
  fmd = FactorMetadata([X0;X1],[:x0;:x1],ARR,:x1,nothing)
  cfo = CalcFactor(fct, fmd, 1, 1, meas, ARR)

  # get a fresh measurement if needed
  meas = length(meas) != 0 ? meas : getSample(cfo, 1)
  cfo = CalcFactor(fct, fmd, 1, 1, meas, ARR)

  # residual vector
  zdim = IIF._getZDim(ccw)
  res = zeros(zdim)

  # calc the residual
  @time res = cfo(meas..., param1, param2)

  return res
end

#


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

include("model_Location.jl")
include("model_LocationListResult.jl")
include("model_LocationMetadata.jl")
include("model_ManagedByTenant.jl")
include("model_Operation.jl")
include("model_OperationDisplay.jl")
include("model_OperationListResult.jl")
include("model_PairedRegion.jl")
include("model_Subscription.jl")
include("model_SubscriptionListResult.jl")
include("model_SubscriptionPolicies.jl")
include("model_TenantIdDescription.jl")
include("model_TenantListResult.jl")


text:
#=
demo_BMM_Gaussian1DGaussian1D.jl

Demo for Bayesian Finite Mixture Model with Gaussian1DGaussian1D conjugates.

08/07/2015
Adham Beyki, odinay@gmail.com
=#

using BNP
srand(123)

## --- synthesizing the data --- ##
true_KK = 5                             # number of components
NN      = 500                           # number of data points

vv = 0.01                               # fixed variance
ss = 2
true_atoms = [Gaussian1D(ss*kk, vv) for kk = 1:true_KK]

mix = ones(Float64, true_KK)/true_KK
xx  = ones(Float64, NN)
true_zz = ones(Int, NN)
true_nn = zeros(Int, true_KK)

for n=1:NN
    kk = sample(mix)
    true_zz[n] = kk
    xx[n] = sample(true_atoms[kk])
    true_nn[kk] += 1
end

## ------- inference -------- ##
# constructing the Gaussian1DGaussian1D conjugate
m0 = mean(xx)
v0 = 2.0
q0 = Gaussian1DGaussian1D(m0, v0, vv)

# constructing the Bayesian Mixture Model
KK = true_KK
bmm_aa = 1.0
bmm = BMM(q0, KK, bmm_aa)

# initializing the cluster labels
zz = zeros(Int, length(xx))
zz = rand(1:bmm.KK, NN)

# sampling
n_burnins    = 100
n_lags       = 2
n_samples    = 200
store_every  = 10000
results_path = ""
filename     = "demo_BMM_Gaussian1DGaussian1D"

collapsed_gibbs_sampler(bmm, xx, zz, n_burnins, n_lags, n_samples, store_every, results_path, filename)

# posterior distributions
posterior_components, nn = posterior(bmm, xx, zz)


text:
include("./Include.jl")

function SolveBalances(TStart, TStop, TStep, dataDictionary)
	t = collect(TStart:TStep:TStop)
	all_species_reversed_dict = dataDictionary["all_species_reversed_dict"]
	# initial species concentration
	y0 = dataDictionary["initial_condition"]
	# call ODE solver
	f(t, y) = Balances(t, y, dataDictionary)
	t, y = ode23s(f, y0, t; points=:specified)

	# data transfer
	row = length(t)
	col = length(y0)
	Y = zeros(row, col)
	foreach(x->(Y[x, :] = y[x]), collect(1:row))
	# plot results
	plt.figure("simulation $TStart to $TStop")
	subplt_col = ceil(Int, col/4)
	for i = 1:col
		plt.subplot(4, subplt_col, i)
		plt.plot(t, Y[:,i])
		plt.title(all_species_reversed_dict[i])
	end
	plt.show()

	return (t, Y)
end

# # uncomment to test
# dataDictionary = generate_model_parameters_dictionary()
# SolveBalances(0, 10, 0.1, dataDictionary)

max_stars_repo_name: varnerlab/SEML

max_issues_repo_name: varnerlab/SEML

max_forks_repo_name: varnerlab/SEML


text:
part1(input) = flash(input, part = 1)
part2(input) = flash(input, part = 2)

function flash(input; part)
    octopi = reduce(hcat, (parse.(Int, collect(line))
                           for line in eachline(input)))
    num_flashes = 0
    i = 0
    while true
        i += 1
        octopi .+= 1
        while true
            flashes = octopi .> 9
            (n = count(flashes)) == 0 && break
            num_flashes += n
            for Δi in -1:1, Δj in -1:1
                Δi == Δj == 0 && continue
                octopi[max(1 + Δi, 1):min(end + Δi, end),
                       max(1 + Δj, 1):min(end + Δj, end)] .+=
                    flashes[max(1 - Δi, 1):min(end - Δi, end),
                            max(1 - Δj, 1):min(end - Δj, end)]
            end
            octopi[flashes] .= -10
        end
        part == 1 && i == 100 && return num_flashes
        octopi .= max.(0, octopi)
        part == 2 && all(==(0), octopi) && return i
    end
end


text:
# Simple test of function run_mut_evolution()
# include("../src/CGP.jl") # Assumes that CGP.jl is loaded
# The following lines allow this file to included from CGP.jl, CGP.jl/test, or CGP.jl/src.
cwd = pwd()
if cwd[end-5:end] == "CGP.jl"
  csvfile = "$cwd/test/data/test_run_mut_evolve.csv"
else
  csvfile = "../test/data/test_run_mut_evolve.csv"
end
iterations = 100
numinputs = 4
numoutputs = 1
nodearity = 2
numinteriors = 16
ngoals = 1
levelsback=numinteriors-4
hamming_rng = true
fault_tol_rng = false
maxsteps = 100000
gl_repetitions=1
#fit_limit_list = [collect(numoutputs)[1]-2.0, collect(numoutputs)[1]-1.0, Float64(collect(numoutputs)[1])]
fit_limit_list = [Float64(collect(numoutputs)[1])]
#run_mut_evolution( iterations, numinputs, numoutputs, numinteriors, goallistlength, maxsteps, levelsback, hamming_rng, fit_limit_list::Vector{Float64}, csvfile )
df =run_mut_evolution( iterations, numinputs, numoutputs, numinteriors, ngoals, maxsteps, levelsback, hamming_rng, fit_limit_list, csvfile, gl_repetitions=gl_repetitions, fault_tol_rng=fault_tol_rng )