How to add value to matrix - list

I want to add value to matrix.
But, I could not do it.
I made the stepfunction for reinforcement learning and I calculated value which named R.
I want to gather R of value and add to matrix named RR.
However, all the calculated values are not added.
Is this because it's done inside a function? If it's not in a function, it works.
Please someone tell me the way to fix it.
% Define the step function
function [NextObservation, Reward, IsDone, LoggedSignals] =
myStepfunction(Action,LoggedSignals,SimplePendulum)
% get the pre statement
statePre = [-pi/2;0];
statePre(1) = SimplePendulum.Theta;
statePre(2) = SimplePendulum.AngularVelocity;
IsDone = false;
% updating states
SimplePendulum.pstep(Action);
% get the statement after updating
state = [-pi/2;0];
state(1) = SimplePendulum.Theta;
state(2) = SimplePendulum.AngularVelocity;
RR = [];
Ball_Target = 10;
Ball_Distance = Ballfunction(SimplePendulum);
R = -abs(Ball_Distance -Ball_Target); ← this the calculated value
RR = [RR,R]; ← I want to add R to RR
if (state(2) > 0) || (SimplePendulum.Y_Position < 0)
IsDone = true;
[InitialObservation, LoggedSignal] = myResetFunction(SimplePendulum);
LoggedSignal.State = [-pi/2 ; 0];
InitialObservation = LoggedSignal.State;
state = InitialObservation;
SimplePendulum.Theta =-pi/2;
SimplePendulum.AngularVelocity = 0;
end
LoggedSignals.State = state;
NextObservation = LoggedSignals.State;
Reward = +max(R);
end

If I understand you correctly, you are trying update RR with this function, and then use/see it outside the loop. This means you need to make two edits:
a) You need to pass RR in and out of the function to update it. You will need to change the first line of your code as shown here, but you will also need to change how you call the function:
function [NextObservation, Reward, IsDone, LoggedSignals, RR] =
myStepfunction(Action,LoggedSignals,SimplePendulum, RR)
b) When you do this RR = [] you delete the content of RR. To initialise RR you will need to move this line to the script that calls this function, making sure it is called before this function is ever called.

Related

How exactly is tensorflow.control_dependecy applied?

self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
with tf.control_dependencies([optimizer_op]):
self.optimizer = control_ops
i call self.optimizer with the session
The code above is not updating the gradients. However if i change the control dependencies part of the code to the one below it works perfectly fine except that it misses out on a final exponential moving average (self.ema_op) update, which is not desirable to me:
self.solver = 'adam'
if self.solver == 'adam':
optimizer = tf.train.AdamOptimizer(self.learning_rate_init)
if self.solver == 'sgd_nestrov':
optimizer = tf.train.MomentumOptimizer(learning_rate = self.learning_rate_init, momentum = self.momentum, \
use_nesterov = True)
gradients, variables = zip(*optimizer.compute_gradients(self.loss))
clipped_gradients, self.global_norm = tf.clip_by_global_norm(gradients, self.max_grad_norm)
update_ops_ = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
optimizer_op = optimizer.apply_gradients(zip(clipped_gradients, variables))
control_ops = tf.group([self.ema_op] + update_ops_)
# with tf.control_dependencies(optimizer_op):
# self.optimizer = control_ops
with tf.control_dependencies([self.ema_op] + update_ops_):
self.optimizer = optimizer.apply_gradients(zip(clipped_gradients, variables))
Please tell me what am i missing?
You need to define the tensorflow operations under the with statement, not just set the variable. Doing self.optimizer = control_ops has no effect because you did not create any tensorflow operations.
Without fully understanding your problem I think you want something like this:
with tf.control_dependencies(optimizer_op):
control_ops = tf.group([self.ema_op] + update_ops_)
self.optimizer = control_ops
The with statement enters a block, under which any new ops you create in tensorflow will be dependent upon optimizer_op in this case.

Access instance variable from instance method in python

class SimpleBond(object):
def__init__(self,OriginationDate,SettleDate,Coupon,CouponFreq,Maturity,Par,StartingPrice = None):
self.CouponCFDaysFromOrigination = np.arange(1,self.NumCouponCFs + 1) * self.CashFlowDelta
self.OriginationCashFlowDates = np.array([self.StartDate + np.timedelta64(int(i),'D') for i in self.CouponCFDaysFromOrigination])
self.StartDate = OriginationDate
def GenerateCashFlowsAndDates(self):
CashFlowDates = self.OriginationCashFlowDates
self.CashFlowDates = CashFlowDates[(CashFlowDates >= self.SettleDate) & (CashFlowDates <=self.MaturityDate)]
I have a class definition as above. Some where else I instantiate the class as below:
BondObj = SimpleBond(OriginationDate = InceptionDate,SettleDate= np.datetime64('2008-02-15'),Coupon = 8.875,CouponFreq = 2,Maturity = 9.5,Par = 100.)
BondObj.GenerateCashFlowsAndDates()
The issue is with the call to GenerateCashFlowDates() as shown above, Once the BondObj is assigned to an instantiation of the SimpleBond class with the arguments to set the state.
When I step inside the call BondObj.GenerateCashFlowsAndDates()....I can see the following state variables
self.StartDate.....its shows the actual state
where
self.OriginationCashFlowDates shows no value. It is none
As a matter of fact, all other instance variables that were set in the constructor are visible from BondObj.GenerateCashFlowAndDates() call
Many thanks

Why does my value of image variable change?

I don't know what happened with my variable. When the variable "amarilloSegm" is inside in the method "Suma_Manchas(amarilloSegm, NecrosadoSegm) it change its value. The strange is that my variable is not modify in all the method.
This is my code, when I call the method:
...
imgManchasUnidas = Suma_Manchas(amarilloSegm, necrosadoSegm)
...
And this is my body of method:
def Suma_Manchas(imagen_1, imagen_2):
imgAma = imagen_1
imgNecro = imagen_2
manchasUnidas = imgAma
y, x = manchasUnidas.shape
for fil in range (0, y):
for col in range (0, x):
# print "x: " + str(fil) + " y: " + str(col)
valUmbral = imgNecro[fil, col]
if (valUmbral > BLANCO-20):
manchasUnidas.itemset((fil, col), BLANCO)
return manchasUnidas
You do imgAma = imagen_1 and then, manchasUnidas = imgAma, and finally modify manchasUnidas, which ends up modifying imagen_1, since it copies the references instead of creating a new object in the memory.
You can do copy.deepcopy() if you want have a brand new object in another part of the memory, so that when you change one, the other one will not be modified.
More specifically:
import copy
def Suma_Manchas(imagen_1, imagen_2):
imgAma = copy.deepcopy(imagen_1)
...

Trouble creating pointer to abstract class

I coded some smiley faces into my app recently, but I'm having trouble calling it in my option interface. The reason I'm wanting to call it from optioninterface is I want to add 2 sets of emojis, and if the value of Setting.nEmoji is 0 or 1 call a different set. The function loademojis() gets called when the application starts (it's technically coded in the interface solution). I can call it from a function that handles user input, but it generated horrible lag, I assume because each time a letter was typed, it cleared the array and loaded the emojis in again. So long story short, I was wondering if there's any way at all to create a pointer to a abstract class so I could call this from my option menu. Everytime I create a pointer and call it from theoption menu it crashes. Here's how I'm creating the pointer
MDrawContext* pDC
void MDrawContext::LoadEmojis()
{
if (Z_VIDEO_EMOJIS == 1)
{
m_Emoji[";)"] = "wink.png";
m_Emoji[":)"] = "smile.png";
m_Emoji[":D"] = "biggrin.png";
m_Emoji[":("] = "frown.png";
m_Emoji[":O"] = "eek.png";
m_Emoji[":P"] = "tongue.png";
m_Emoji[":?"] = "confused.png";
m_Emoji[":4"] = "cool.png";
m_Emoji[":3"] = "redface.png";
m_Emoji[":#"] = "mad.png";
m_Emoji[":I"] = "rolleyes.png";
m_Emoji[":K"] = "kappa.png";
}
else
{
m_Emoji[";)"] = "wink2.png";
m_Emoji[":)"] = "smile2.png";
m_Emoji[":D"] = "biggrin2.png";
m_Emoji[":("] = "frown2.png";
m_Emoji[":O"] = "eek2.png";
m_Emoji[":P"] = "tongue2.png";
}
}
//custom: reloademojis allows players to choose between ios/forum emojis
void MDrawContext::ReloadEmojis()
{
m_Emoji[";)"].clear();
m_Emoji[":)"].clear();
m_Emoji[":D"].clear();
m_Emoji[":("].clear();
m_Emoji[":O"].clear();
m_Emoji[":P"].clear();
m_Emoji[":?"].clear();
m_Emoji[":4"].clear();
m_Emoji[":3"].clear();
m_Emoji[":#"].clear();
m_Emoji[":I"].clear();
m_Emoji[":K"].clear();
LoadEmojis();
}
//Calling the pointer (different cpp)
int nEmojiType = 0;
if(nEmojiType != Z_VIDEO_EMOJI)
{
pDC->ReloadEmojis();
nEmojiType = Z_VIDEO_EMOJI;
}

Subsonic 3 Save() then Update()?

I need to get the primary key for a row and then insert it into one of the other columns in a string.
So I've tried to do it something like this:
newsObj = new news();
newsObj.name = "test"
newsObj.Save();
newsObj.url = String.Format("blah.aspx?p={0}",newsObj.col_id);
newsObj.Save();
But it doesn't treat it as the same data object so newsObj.col_id always comes back as a zero. Is there another way of doing this? I tried this on another page and to get it to work I had to set newsObj.SetIsLoaded(true);
This is the actual block of code:
page p;
if (pageId > 0)
p = new page(ps => ps.page_id == pageId);
else
p = new page();
if (publish)
p.page_published = 1;
if (User.IsInRole("administrator"))
p.page_approved = 1;
p.page_section = staticParent.page_section;
p.page_name = PageName.Text;
p.page_parent = parentPageId;
p.page_last_modified_date = DateTime.Now;
p.page_last_modified_by = (Guid)Membership.GetUser().ProviderUserKey;
p.Add();
string urlString = String.Empty;
if (parentPageId > 0)
{
urlString = Regex.Replace(staticParent.page_url, "(.aspx).*$", "$1"); // We just want the static page URL (blah.aspx)
p.page_url = String.Format("{0}?p={1}", urlString, p.page_id);
}
p.Save();
If I hover the p.Save(); I can see the correct values in the object but the DB is never updated and there is no exception.
Thanks!
I faced the same problem with that :
po oPo = new po();
oPo.name ="test";
oPo.save(); //till now it works.
oPo.name = "test2";
oPo.save(); //not really working, it's not saving the data since isLoaded is set to false
and the columns are not considered dirty.
it's a bug in the ActiveRecord.tt for version 3.0.0.3.
In the method public void Add(IDataProvider provider)
immediately after SetIsNew(false);
there should be : SetIsLoaded(true);
the reason why the save is not working the second time is because the object can't get dirty if it is not loaded. By adding the SetIsLoaded(true) in the ActiveRecord.tt, when you are going to do run custom tool, it's gonna regenerate the .cs perfectly.