I am trying to fit a non-linear model using nls function. The model has a conditioning and works by groups therefore I try to implement a loop which covers over 300 combinations of starting values. I am using tryCatch but to my surprise the loop crashes, I guess because of the starting values or lower and upper bounds.
tryCatch(
for(r in 1:nrow(st4)){
halfLE3[[r]] <- nls(
inty ~ I(time < (position/velocity) + dinitial) * Inty_S0 +
(time >= (position/velocity) + dinitial) *
I(Intyf[probe] + (Inty_S0[probe] - Intyf) *
(exp(-Decay * (time - (position/velocity) + dinitial)))),
data = Data4,
algorithm = "port",
control = list(warnOnly = TRUE),
start = list(Decay=st4[r,3], dinitial=st4[r,2],
Intyf=rep(st4[r,4], length(levels(Data4$probe))),
Inty_S0=rep(st4[r,5], length(levels(Data4$probe))),
velocity=st4[r,1]),
lower = list(Decay= .1, dinitial=0.1, velocity=10, Intyf=0.1, inty_S0=.5),
upper = list(Decay= 1, dinitial=10, velocity=8000, Intyf=1, inty_S0=1.5)
)
}
,error = function(e) {e}
)
st4 is a dataframe with 300 combinations of starting values.
probe refers to group.
Do you have any idea why the loop crashes even using the tryCatch? Do you have any idea what I can improve? I used the nls.control changing the maxiter and other parameters but works same as the control I use here above.
I would be very grateful for any suggestion.
I fixed the issue. The tryCatch should be located inside the for loop adding a bracket.
for(r in 1:nrow(st4)){
tryCatch({
nls()......
},error = function(e) {e}
)
}
Related
I´ve noticed that some custom modules that I develop can be installed on databases with records, while others throw the KeyError message, unless the database is empty (no records). Generally the errors appear when the module contains computed fields. So, does anybody know why this happens? and how my code should look like to avoid this kind of errors?
an example computed field that throws this errors looks like this:
from odoo import models, fields, api
from num2words import num2words
Class InheritingAccountMove(models.Model):
_inherit = 'account.move'
total_amount_text = fields.Char(string='Total', compute='_compute_total_amount_text', store=True)
#api.depends('amount_total')
def _compute_total_amount_text(self):
lang_code = self.env.context.get('lang') or self.env.user.lang
language = self.env['res.lang'].search([('iso_code', '=', lang_code)])
separator = language.read()[0]['decimal_point']
for record in self:
decimal_separator = separator
user_language = lang_code[:2]
amount = record.amount_total
amount_list = str(amount).split(decimal_separator)
amount_first_part = num2words(int(amount_list[0]), lang=user_language).title() + ' '
amount_second_part = amount_list[1]
if len(amount_second_part) == 0:
amount_text = amount_first_part + '00/100'
elif len(amount_second_part) < 2:
amount_text = amount_first_part + amount_second_part + '0/100'
else:
amount_text = amount_first_part + amount_second_part[:2] + '/100'
record.total_amount_text = amount_text
UPDATED
The reason your code has a problem in this situation is that when there are no records in the table(at time of installation) your loop won’t run which result in no value assigning of your computed field so
Add the first line of code in function
self.total_amount_text = False This is required to assign value to the computed field in compute function from Odoo 13 and maybe 12
----------------------------------------------------------------
Other reasons could be :
This error occurs when one tries to access a key from a dictionary that doesn't exist like,
language.read()[0]['decimal_point']
the dictionary may not have 'decimal_point' at the time of installation of the module, which may have returned this error a common way to handle this is by checking if the key exists or not before accessing it like,
if 'decimal_point' in language.read()[0].keys()
also, a dictionary can also be empty in that case the language.read()[0] will throw an error
I´ve changed my code making it specifically for spanish and the error doesn´t appear anymore. I appreciate Muhammad´s answer, maybe he´s right but anyway here is the modified code:
#api.depends('invoice_line_ids')
def _compute_total_amount_text(self):
for record in self:
amount = record.amount_total
amount_list = str(amount).split('.')
amount_first_part = num2words(int(amount_list[0]), lang='es').title() + ' '
amount_second_part = amount_list[1]
if len(amount_second_part) == 0:
amount_text = amount_first_part + '00/100'
elif len(amount_second_part) < 2:
amount_text = amount_first_part + amount_second_part + '0/100'
else:
amount_text = amount_first_part + amount_second_part[:2] + '/100'
record.total_amount_text = amount_text
because I cant find any way to test my Pine Script strategy on multiple symbols, I created a way to loop through my whole Script.
In This I made 10 variables for 10 different Symbols like this:
ersteTicker = "AAPL"
zweiteTicker = "MSFT"
dritterTicker = "..."
Than I loopedfrom 1 to 10 and made 10 If-querys, which give me in every loop the right symbol like this:
a = 1
for i = 0 to 10
if a == 1
tickerID = ersteTicker
if a == 2
tickerID = .....
Now I thougt everything should be all right, but now the console gives back an error message called:
line 75: Can't call 'security' inside: 'if', 'for'
Does anybody know how to bypass this problem??
best regards
Christian
P.S.: I already tested a small other script and in this script the console doesn't give me back this error message, even if I also made a for loop with a security function in it..
(looks like this)
//#version=3
strategy("Meine Strategie", overlay=true)
tickerID = "ADS"
vergleichstimeframe = "D"
TaesRSLPeriode = 200
a = 1
myEma() => ema(close, TaesRSLPeriode)
for i = 0 to 10
if ( a == 1)
Daily_ema = security(tickerID, vergleichstimeframe, myEma())
//plot(Daily_ema*TagesRSLGrenzwert)
longCondition = crossover(sma(close, 14), sma(close, 28))
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortCondition = crossunder(sma(close, 14), sma(close, 28))
if (shortCondition)
strategy.entry("My Short Entry Id", strategy.short)
Here's an example of global security. The security must not be inside of neither for nor if statements. If you need more symbols - use more securities. But bear in mind, that you can't choose a symbol from a set of symbols and call security with that symbol (because it'll be mutable variable and you cannot use them with security):
//#version=3
strategy("Meine Strategie", overlay=true)
tickerID = "ADS"
vergleichstimeframe = "D"
TaesRSLPeriode = 200
a = 1
myEma() => ema(close, TaesRSLPeriode)
// this always must stay global
Daily_ema = security(tickerID, vergleichstimeframe, myEma())
// here you could put more secureties:
//Daily_ema1 = security(tickerID1, vergleichstimeframe, myEma())
//Daily_ema2 = security(tickerID2, vergleichstimeframe, myEma())
//Daily_ema3 = security(tickerID3, vergleichstimeframe, myEma())
// ...
for i = 0 to 10
if a == 1
if Daily_ema > Daily_ema[i] // actual using of the security's result
strategy.entry("My Long Entry Id", strategy.long)
In general and according to previous comments, the strategy tester isn’t accurate. Just view an indication for the operation. Maybe the only benefit of the testing strategy is to determine the value of (SL, TP). Meanwhile the strategy depends on trusted intermittent periods, you can increase the SL 10 to avoid the temporary reflections
In Julia, I'd like to update a plot upon the change of value in a Gtk Slider. I understand that this has to do with the "change-value" signal in https://developer.gnome.org/gtk2/2.24/GtkRange.html#GtkRange-value-changed. However, as a beginner, I do not know how to implement the code
The “change-value” signal
gboolean
user_function (GtkRange *range,
GtkScrollType scroll,
gdouble value,
gpointer user_data)
to achieve what I wanted to do. Could anyone kindly provide an example how to use the "change-value" signal?
I know how to set up a window for the slider
sl = slider(1:11)
win = Window("Testing") |> (bx = Box(:v))
push!(bx, sl)
Gtk.showall(win)
I also know what kind of function I need to update the plot
function update(val)
int_val = int(val)
if Signal(sl) != int_val
x = range(0., 2*pi, step=0.01)
y = map(sin, x)
PyPlot.plot(x,Signal(sl)*y)
end
end
However, I don't know how or where I can trigger the "update" function to take actual action.
Thanks!
Thanks, liberforce for your advice!
Here is my minimal working example:
'''
using Gtk
# Set up scale (slider) and window
sl = GtkScale(false, 0:10)
win = Gtk.Window("Gain Selection") |> (bx = Gtk.Box(:v))
push!(bx, sl)
Gtk.showall(win)
# Connect with value-changed signal
id = signal_connect(sl, "value-changed") do widget
# Get scale value
sub = Gtk.GAccessor.adjustment(widget)
val = Gtk.get_gtk_property(sub,"value",Int64)
# Perform function related to the scale value.
println("Gain is changed to ", val)
end
push!(bx, sl)
Gtk.showall(win);
'''
Reference:
signal connect: http://juliagraphics.github.io/Gtk.jl/latest/manual/signals.html
GtkScale: https://lazka.github.io/pgi-docs/Gtk-3.0/classes/Scale.html
Extract scale value: https://discourse.julialang.org/t/how-to-get-the-current-value-of-a-gtk-scale-widget/15680
Julia Do-block: https://www.juliabloggers.com/julia-do-block-vs-python-with-statement/
after an update to Sierra I had to find that Karabiner is not working anymore, which could emulate pointer clicks really well.
Any chance to get that via Swift or Apple Script or Obj.C ?
Background: Using Karabiner(and seil) I could bind caps-lock + d down and up to mouse down and up and in between the trackpad movement was understood. My trackpad is not processing keypress anymore but works still fine for pointer moves.
Answering myself, hacked it in hammerspoon. Was quite tricky to get chrome select working, maybe it saves somebody an hour or two:
1 ~/.hammerspoon $ cat init.lua
--[[ Left Keyboard Mouse (alt-d)
The main problem was to get chrome based apps select text when we drag via
keyboard.
You MUST return true always in the handle_drag otherwise it fails to select.
FF works, terminal works, chrome apps (atom, ...) don't.
But true is preventing further processing of the drag coords,
hs.mouse.getAbsolutePosition remains constant while dragging (!)
=> i.e. we MUST calc them via DeltaX, DeltaY, see below.
--]]
hs.alert.show("Config loaded")
-- all mechanics stolen from here:
-- local vimouse = require('vimouse')
-- vimouse('cmd', 'm')
now = hs.timer.secondsSinceEpoch
evt = hs.eventtap
evte = evt.event
evtypes = evte.types
evp=evte.properties
drag_last = now(); drag_intv = 0.01 -- we only synth drags from time to time
mp = {['x']=0, ['y']=0} -- mouse point. coords and last posted event
l = hs.logger.new('keybmouse', 'debug')
dmp = hs.inspect
-- The event tap. Started with the keyboard click:
handled = {evtypes.mouseMoved, evtypes.keyUp }
handle_drag = evt.new(handled, function(e)
if e:getType() == evtypes.keyUp then
handle_drag:stop()
post_evt(2)
return nil -- otherwise the up seems not processed by the OS
end
mp['x'] = mp['x'] + e:getProperty(evp.mouseEventDeltaX)
mp['y'] = mp['y'] + e:getProperty(evp.mouseEventDeltaY)
-- giving the key up a chance:
if now() - drag_last > drag_intv then
-- l.d('pos', mp.x, 'dx', dx)
post_evt(6) -- that sometimes makes dx negative in the log above
drag_last = now()
end
return true -- important
end)
function post_evt(mode)
-- 1: down, 2: up, 6: drag
if mode == 1 or mode == 2 then
local p = hs.mouse.getAbsolutePosition()
mp['x'] = p.x
mp['y'] = p.y
end
local e = evte.newMouseEvent(mode, mp)
if mode == 6 then cs = 0 else cs=1 end
e:setProperty(evte.properties.mouseEventClickState, cs)
e:post()
end
hs.hotkey.bind({"alt"}, "d",
function(event)
post_evt(1)
handle_drag:start()
end
)
and alt I mapped to capslock via karabiner elements.
We are trying to read the pixels from an uploaded Bitmap image, yet the line
aBrightness = (0.2126*aPixel[1].red) + (0.7152*aPixel[1].green) + (0.0722*aPixel[1].blue) always gives an error saying "Unknown property: "red" in undefined".
Our current script is:
aBitmap = selectBitMap caption:"Select a Bitmap"
Print(aBitmap.height)
Print(aBitmap.width)
aLength = aBitmap.height
aWidth = aBitmap.width
for i = 0 to (aLength - 10) by 10 do
(
for j = 0 to (aWidth - 10) by 10 do
(
Print(i)
Print(j)
aPixel = getPixels aBitmap [i,j] 1
aBrightness = (0.2126*aPixel[1].red) + (0.7152*aPixel[1].green) + (0.0722*aPixel[1].blue)
aBox = box pos:[i,j,0] width:0.1 length:0.1 height:aBrightness
)
)
We would really appreciate any help regarding this script.
You have your coordinates wrong. The X value goes first.
It should be
APixels = Getpixels aBitmap [j, i] 1
You can check to see if aPixel is undefined before using it.
aPixel = getPixels aBitmap [i,j] 1
if (aPixel == undefined) do ( format "ERROR!!! [%,%]\n" i, j to:listener; continue )
aBrightness = (0.2126*aPixel[1].red) + (0.7152*aPixel[1].green) + (0.0722*aPixel[1].blue)
This might help you figure where the bug is. Often a function will return 'undefined' to a variable so you need to check if it is undefined. In this case, once you fix the bug, you can remove this type of code since you will have eliminated undefined behavior. Notice I used "format" instead of "print", this is much nicer to use for just a tiny extra code.
I see two suspicious things to check.
1) Most indexing in maxscript starts with 1 not 0. Check the documentation.
2) As Rotem pointed out, [x,y], not [y,x]