Regarding incorporating piecewise function in ode using octave code - octave

Differential equation where M_v is a piecewise function
Differential equation where M_v is a piecewise function
Piecewise function
I have coded the differential equation in Octave using the RUnge-Kutta 4 (RK4) method. However, the result is not as desired due to the piecewise function being coded incorrectly in my view. Could anyone help to code piecewise function correctly to solve differential equation using rk4 method?
%vIRt code of the equations given in the manuscript
function x = pieceWise(s)
x = zeros (size (s));
ind = s > 0;
x(ind) = s(ind);
endfunction
% Defines variables
global tau_s taur_a beta_r I_ext J_inter J_intra Jr_a I_0 lp;
tau_s = 10; taur_a = 83; beta_r = 0.0175; Jr_a = 172.97; J_inter= 81; J_intra = 32.4; I_0= 0.29; I_ext = 20;
% step sizes
t0 = 0;
tfinal = 200;
h = 0.05;
n = ceil((tfinal-t0)/h)+1;
%initial conditions
s_r(1) = 0;
s_p(1) = 0.3556;
a_p(1) = 6.151;
a_r(1) = 0;
t(1) =0;
% functions handles
S_r = #(t,s_r,s_p,a_r,a_p) -(s_r/tau_s)+ beta_r*pieceWise(I_ext-J_intra*s_r-J_inter*s_p-a_r-I_0);
A_r = #(t,s_r,s_p,a_r,a_p) (-a_r+Jr_a*beta_r*pieceWise(I_ext-J_intra*s_r-J_inter*s_p-a_r-I_0))/taur_a;
S_p = #(t,s_r,s_p,a_p,a_r) -(s_p/tau_s)+ beta_r*pieceWise(I_ext-J_inter*s_r-J_intra*s_p-a_p-I_0);
A_p = #(t,s_r,s_p,a_p,a_r) (-a_p+Jr_a*beta_r*pieceWise((I_ext-J_inter*s_r-J_intra*s_p-a_p-I_0)))/taur_a;
for i = 1:n
%updates time
t(i+1) = t(i)+h;
%updates S_r, A_r, S_p and A_p
k1S_r = S_r(t(i), s_r(i), s_p(i), a_r(i), a_p(i));
k1A_r = A_r(t(i), s_r(i), s_p(i), a_r(i), a_p(i));
k1S_p = S_p(t(i), s_r(i), s_p(i), a_r(i), a_p(i));
k1A_p = A_p(t(i), s_r(i), s_p(i), a_r(i), a_p(i));
k2S_r = S_r(t(i)+h/2, s_r(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2S_r + 2*k3S_r +k4S_r);
s_p(i+1) = s_p(i)+h/6*(k1S_p + 2*k2S_p + 2*k3S_p +k4S_p);
a_r(i+1) = a_r(i)+h/6*(k1A_r + 2*k2A_r + 2*k3A_r +k4A_r);
a_p(i+1) = a_p(i)+h/6*(k1A_p + 2*k2A_p + 2*k3A_p +k4A_p);
end
M_r = beta_r*pieceWise((I_ext-J_intra*s_r-J_inter*s_p-a_r-I_0));
M_p = beta_r*pieceWise((I_ext-J_inter*s_r-J_intra*s_p-a_p-I_0));
%plots
##plot(t,M_p)
##hold on
##plot(t,M_r)
##plot(t,s_r)
##hold on
##plot(t,s_p)
##hold on
##plot(t,a_p)
##hold on
##plot(t,a_r)
##title('a_p and a_r')
##legend('s_r', 's_p', 'position', 'best')
##xlim([0,200])
drawnow;
%print -deps rk4.eps

Related

Can we recall a set of variable inside the Sequence Array?

I'd like to ask about my program bcs it doesn't work correctly. I want to recall a set of variable in two different Sequence Array. Here is my code.
// Array of Arrays
var SequenceGo:Array =
\[
{dt:dt1, P:P1, s0:s01, s:s1},
{dt:dt2, P:P2, s0:s02, s:s2},
{dt:dt3, P:P3, s0:s03, s:s3},
{dt:dt4, P:P4, s0:s04, s:s4},
{dt:dt5, P:P5, s0:s05, s:s5},
{dt:dt6, P:P6, s0:s06, s:s6},
{dt:dt7, P:P7, s0:s07, s:s7},
{dt:dt8, P:P8, s0:s08, s:s8},
{dt:dt9, P:P9, s0:s09, s:s9},
{dt:dt10, P:P10, s0:s010, s:s10},
\];
var SequenceBack:Array =
\[
{dtback:dt10back, P:P10, s0:s010, sback:s10back},
{dtback:dt9back, P:P9, s0:s09, sback:s9back},
{dtback:dt8back, P:P8, s0:s08, sback:s8back},
{dtback:dt7back, P:P7, s0:s07, sback:s7back},
{dtback:dt6back, P:P6, s0:s06, sback:s6back},
{dtback:dt5back, P:P5, s0:s05, sback:s5back},
{dtback:dt4back, P:P4, s0:s04, sback:s4back},
{dtback:dt3back, P:P3, s0:s03, sback:s3back},
{dtback:dt2back, P:P2, s0:s02, sback:s2back},
{dtback:dt1back, P:P1, s0:s01, sback:s1back}
\];
function onNext(index:int = 0):void
{
if (index >= SequenceGo.length)
{
return;
}
var aDataGo:Object = SequenceGo[index];
var aDataBack:Object = SequenceBack[index];
//variables
F = s_teganganst.value;
m = s_masjenst.value/10000;
v = Math.sqrt(F/m);
tp = 5000/v;
f = s_frekuensist.value;
w = 2*Math.PI*f;
aDataGo.dt += t;
aDataGo.s = aDataGo.s0 - A * Math.sin(w * aDataGo.dt);
aDataGo.P.y = aDataGo.s;
if(P10.y < 607){
aDataBack.dtback += t;
aDataBack.sback = - A * Math.sin(w * aDataBack.dtBack);
aDataBack.P.y = aDataGo.s + aDataBack.sback;
}
setTimeout(onNext, tp, index + 1);
}
Actually, code
aDataBack.P.y = aDataGo.s + aDataBack.sback;
is not a fit code for the animation because aDataBack is ordered inversely from aDataGo (we have to stay this inverse order for the proper animation in my program). I want to recall the variables based on its number, so each variable will match with another variable. For example,
P1.y = s1 + s1back;
P2.y = s2 + s2back;
P3.y = s3 + s3back;
P4.y = s4 + s4back;
//and so on
I've tried the code above, but it also doesn't work. Any other expression for calling some couples of variables just like my code above? Thanks!
I want to recall the variables based on its number, so each variable will match with another variable
Ok, there are two options.
Option one, simple and straightforward: compose a method to find the correspondent back object on spot:
function findBack(P:Object):Object
{
for each (var aDataBack:Object in SequenceBack)
{
if (aDataBack.P == P)
{
return aDataBack;
}
}
}
So, that piece of code would be
var aDataGo:Object = SequenceGo[index];
var aDataBack:Object = findBack(aDataGo.P);
The possible problem here is the performance. It is fine on the scale of 10 or 100 objects, but as (I suppose) you devise a particle system, the object count easily scales to thousands, and the amount of loop-searching might become cumbersome.
So I advise to prepare a pre-indexed hash so that you won't need to search each single time.
var SequenceBack:Array =
[
// ...
];
// Dictionary is a storage of key:value data, just like Object,
// but Dictionary allows Object keys.
var HashBack:Dictionary = new Dictionary;
for each (var aDataBack:Object in SequenceBack)
{
HashBack[aDataBack.P] = aDataBack;
}
I encourage you to read more about Dictionary class.
And so that piece of code would be
var aDataGo:Object = SequenceGo[index];
var aDataBack:Object = HashBack[aDataGo.P];

ion-input type number becomes unresponsive when holding down the delete key on device

I'm having an issue with an ion-input, which drops this error below when holding down the delete key.
"Error: Invalid argument '' for pipe 't'
at new Error (native)
at Error.v (file:///android_asset/www/build/polyfills.js:3:4864)
at e [as constructor] (file:///android_asset/www/build/main.js:94:11171)
at new e (file:///android_asset/www/build/main.js:14:10469)
at n (file:///android_asset/www/build/main.js:9:10302)
at t.transform (file:///android_asset/www/build/main.js:9:11000)
at file:///android_asset/www/build/main.js:1:17764
at e.detectChangesInternal (file:///android_asset/www/build/main.js:125:10032)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)
at e.t.internalDetectChanges (file:///android_asset/www/build/main.js:4:8640)
at e.detectChangesInternal (file:///android_asset/www/build/main.js:120:27362)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)
at t.detectChangesInNestedViews (file:///android_asset/www/build/main.js:4:28534)
at e.detectChangesInternal (file:///android_asset/www/build/main.js:80:24234)
at e.t.detectChanges (file:///android_asset/www/build/main.js:4:8847)", source: file:///android_asset/www/build/main.js (29)
This one below is my ion-input:
<ion-input color="primary_light" [(ngModel)]="montco_ui" type="number
(keyup)="formataNumero()"></ion-input>
Also, I'm using this algorithm to handle 2 decimal places, which is working fine, since I guess the issue is related to the type number property on the ion-input.
formataNumero(separador: string = '.', decimais: number = 2) {
console.log('formataNumero called');
let a: any = this.montco_ui.split('');
let ns: string = '';
a.forEach((c: any) => { if (!isNaN(c)) ns = ns + c; });
ns = parseInt(ns).toString();
if (ns.length < (decimais + 1)) {
ns = ('0'.repeat(decimais + 1) + ns);
ns = ns.slice((decimais + 1) * -1);
}
let ans = ns.split('');
let r = '';
for (let i = 0; i < ans.length; i++)
if (i == ans.length - decimais) {
r = r + separador + ans[i]; else r = r + ans[i];
}
this.montco_ui = r;
}
Finally, this is the variable that keeps the value:
P.S.: I'm using Ionic 2 for my project.
public montco_ui: string = "0.00";

How to Create Parametric Survival Learner for MLR in R

I am following the instructions (https://mlr.mlr-org.com/articles/tutorial/create_learner.html) to create a parametric survival learner to use with MLR. My code is below.
When I try to make the MakeLearner(id = "AFT", "surv.parametric"), I get an error
dist is missing and no default is set even though I already specified the dist default in my code to be "weibull".
makeRLearner.surv.parametric = function() {
makeRLearnerSurv(
cl = "surv.parametric",
package = "survival",
par.set = makeParamSet(
makeDiscreteLearnerParam(id = "dist", default = "weibull",
values = c("weibull", "exponential", "lognormal", "loglogistic")),
),
properties = c("numerics", "factors", "weights", "prob", "rcens"),
name = "Parametric Survival Model",
short.name = "Parametric",
note = "This is created based on MLR3 surv.parametric learner"
)
}
trainLearner.surv.parametric = function (.learner, .task, .subset, .weights = NULL, ...)
{
f = getTaskFormula(.task)
data = getTaskData(.task, subset = .subset)
if (is.null(.weights)) {
mod = survival::survreg(formula = f, data = data, ...)
}
else {
mod = survival::survreg(formula = f, data = data, weights = .weights, ...)
}
mod
}
predictLearner.surv.parametric = function (.learner, .model, .newdata, ...)
{
survival::predict.survreg(.model$learner.model, newdata = .newdata, type = "response", ...)
}
Based on here, the prediction function needs to return linear predictors and that would be lp not response. Also, the cindex function of MLR does not seem to be consistent with the output of SurvReg. Based on this discussion, adding a minus seems to resolve the issue. So the prediction function would be as below.
predictLearner.surv.reg = function(.learner, .model, .newdata, ...) {
-predict(.model$learner.model, newdata = .newdata, type = "lp", ...)
}

Computation of loss is taking very much time on GPU in pytorch

I've been trying to implement DCGAN in pytorch. But during training, a single iteration of training loop takes more than 7-8 minutes on GPU on google collab. I can't understand what is wrong in the code. I have been trying many techniques to overcome this issue but nothing seems to be working..
Here's My training loop and it was taking more than 7-8 minutes on a single iteration:
device = torch.device("cuda:0")
dis = Discriminator().to(device)
Gen = Generator().to(device)
GAN_loss = nn.BCELoss().to(device)
D_optimizer = optim.Adam(dis.parameters(), lr = 0.0002, betas = (0.5, 0.999))
G_optimizer = optim.Adam(Gen.parameters(), lr = 0.0002, betas = (0.5, 0.999))
path = 'gdrive/My Drive/New_data/'
path2 = 'gdrive/My Drive/New_cropped/'
train_data_list = os.listdir(path)
train_data_len = len(train_data_list)
minibatch_size = 64
epochs = 10
G_losses = []
D_losses = []
final_itr = (train_data_len + minibatch_size - 1) // minibatch_size
data_list = [train_data_list[i * minibatch_size : (i + 1) * minibatch_size] for i in range(final_itr)]
for epoch in range(epochs):
for count, data in enumerate(data_list):
train_img = []
sample_img = []
for image in data:
img_train = cv2.imread(path + image).T/255
img_train = img_train.reshape(1, img_train.shape[0], img_train.shape[1], img_train.shape[2])
img_sample = cv2.imread(path2 + image,0).T/255
img_sample = img_sample.reshape(1, 1, img_sample.shape[0], img_sample.shape[1])
train_img.append(img_train)
sample_img.append(img_sample)
assert(img_sample.shape == (1, 1, 144, 144))
train_image = Variable(torch.from_numpy(np.concatenate(train_img, axis = 0)).cuda())
sample_image = Variable(torch.from_numpy(np.concatenate(sample_img, axis = 0)).cuda())
label = torch.full((train_image.shape[0],), real_label, device=device)
#Training the discriminator... minimizing -(log(D(x)) - log(1 - D(G(Z))))
dis.zero_grad()
Gen.zero_grad()
G_z = Gen(sample_image.detach())
disc_real_out = dis(train_image.detach()).view(-1)
error_real = GAN_loss(disc_real_out, label)
error_real.backward()
disc_fake_out = dis(G_z.detach()).view(-1)
label.fill_(fake_label)
error_fake = GAN_loss(disc_fake_out, label)
error_fake.backward()
total_disc_error = error_real + error_fake
D_optimizer.step()
#Training the Generator... maximizing log(D(G(Z))))
D_G_z = dis(G_z.detach()).view(-1)
label.fill_(real_label)
error_gen = GAN_loss(D_G_z, label)
error_gen.backward()
G_optimizer.step()
G_losses.append(error_gen.item())
D_losses.append(total_disc_error.item())
print("Discriminator Loss : ", total_disc_error.item(), "\t", "Generator Loss : ", error_gen.item())

Set XML .#<index> based on interator AS3

In AS3 is it possible to export multiple iterations of the same variable as seen in the below example:
var item:String = "obj";
var child:XML = new XML(<{item}/>);
child.#x = String(object.x);
child.#y = String(object.y);
child.#n = String(object.name);
child.#w = String(object.width);
child.#h = String(object.height);
//...instead of:
child.#s = String(object.sprite);
//...is the below possible:
for (i = 0; i < <length>; ++i) {
child.#s[i] = String(object.get_sprite(i));
}
//...desired <filename>.xml output:
obj.s0 = "sprite_0"
obj.s1 = "sprite_1"
obj.s2 = "sprite_2"
obj.s3 = "sprite_3"
etc..
Haven't worked on AS3 for a while now, but if I remember correctly you should be able to do:
for (i = 0; i < <length>; ++i) {
var attrName = "s" + i.toString();
child.#[attrName] = String(object.get_sprite(i));
}
Sorry, I don't have tools available to try it out myself, but should work.