I create many test interface parameters during the $dut initialization. The app inits the model in either 'load' or 'import' mode, as we get many sources of info from 3rd parties. For parameters, the source is native Ruby so regardless of the init method (load or import) the code is required like this:
send modeling_method, model_path # load_params or import_params
Here is that method(s):
def load_params(path)
Origen.log.info("PPEKit: Modeling parameters from #{path}")
require path.to_s.chomp('.rb')
Origen.log.info("PPEKit: Modeling of parameters complete")
end
alias_method 'import_params', 'load_params'
Here is the content of the file required above:
Origen.top_level.define_params :default do |params|
params.bist.override = 1
params.bist.lev_equ_set = 1
params.bist.lev_spec_set = 1
params.bist.levset = 1
params.bist.seqlbl = 'mbist_cpu_hr_vnom_burst'
params.bist.override_tim_spec_set = 'bist_25Mhz'
params.bist.override_timset = '1,1,1,1,1,1,1,1'
params.bist.site_control = 'parallel:'
params.bist.site_match = 2
end
I can see them at the end of my $dut initialization during execution of the command 'origen p myflowfile.rb':
[5] pry(#<PPEKit::Product>)> $dut.params
=> {:bist=>
{:override=>1,
:lev_equ_set=>1,
:lev_spec_set=>1,
:levset=>1,
:seqlbl=>"mbist_cpu_hr_vnom_burst",
:override_tim_spec_set=>"bist_25Mhz",
:override_timset=>"1,1,1,1,1,1,1,1",
:site_control=>"parallel:",
:site_match=>2}}
However, when Origen transitions to the test interface code, the params are not accessible:
[1] pry(#<STP::Interface>)> $dut.params
=> #<Origen::Parameters::Missing:0x002aaab22dc378
#owner=<Model/Controller: PPEKit::Product:23456337817000/PPEKit::ProductController:23456355062960>>
I can, however, see other parts of the $dut model such as pins and sub_blocks:
[2] pry(#<STP::Interface>)> $dut.sub_blocks
=> {"block0"=><Model: PPEKit::Product::Block0:23456336916760>,
"block1"=><Model: PPEKit::Product::Block1:23456336907380>,
"block2"=><Model: PPEKit::Product::Block2:23456336841100>,
It just seems like they are getting erased sometime between the model init and the test flow generation. So I put a breakpoint in the 'on_load_target' callback, and saw different results each time the breakpoint was hit. On the first break, the params were there and on subsequent breaks they were not.
75: def on_load_target
=> 76: binding.pry
77: to_origen(path: vendor_path.to_s, instantiate_level: :sub_block) if #import
78: end
[1] pry(#<PPEKit::Product>)> $dut.params
=> {:bist=>
{:override=>1,
:lev_equ_set=>1,
:lev_spec_set=>1,
:levset=>1,
:seqlbl=>"mbist_ccx_hr_vnom_burst",
:override_tim_spec_set=>"bist_25Mhz",
:override_timset=>"1,1,1,1,1,1,1,1",
:site_control=>"parallel:",
:site_match=>2}}
[2] pry(#<PPEKit::Product>)>
Frame number: 0/25
From: /users/user/origen/ppekit/lib/ppekit/product.rb # line 76 PPEKit::Product#on_load_target:
75: def on_load_target
=> 76: binding.pry
77: to_origen(path: vendor_path.to_s, instantiate_level: :sub_block) if #import
78: end
[1] pry(#<PPEKit::Product>)> $dut.params
=> #<Origen::Parameters::Missing:0x002aaab9f3ad48
#owner=<Model/Controller: PPEKit::Product:23456377300040/PPEKit::ProductController:23456379739240>>
I believe there could be 2 issues here:
1) The repeated initialization of the $dut during test flow generation, documented here
2) The emptying of the parameter set hash, which is due to issue #1 (and some Parameter set initialization code
I believe it has something to do with the parameter #owner being defined as the $dut instance during the parameter definition and #owner being re-defined as the $dut ProductController instance on subsequent queries of the parameters.
thx
The problem here is that the parameters are ultimately getting loaded by calling require 'some_file.rb'.
Whenever the target is internally re-loaded, Ruby hits the line again but does not do anything since it knows that it has already required that file and effectively skips over that line.
Changing it to load 'some_file.rb' will force it to execute the file every time.
Related
I'm a student teaching myself Drake, specifically pydrake with Dr. Russ Tedrake's excellent Underactuated Robotics course. I am trying to write a combined energy shaping and lqr controller for keeping a cartpole system balanced upright. I based the diagram on the cartpole example found in Chapter 3 of Underactuated Robotics [http://underactuated.mit.edu/acrobot.html], and the SwingUpAndBalanceController on Chapter 2: [http://underactuated.mit.edu/pend.html].
I have found that due to my use of the cart_pole.sdf model I have to create an abstract input port due receive FramePoseVector from the cart_pole.get_output_port(0). From there I know that I have to create a control signal output of type BasicVector to feed into a Saturation block before feeding into the cartpole's actuation port.
The problem I'm encountering right now is that I'm not sure how to get the system's current state data in the DeclareVectorOutputPort's callback function. I was under the assumption I would use the LeafContext parameter in the callback function, OutputControlSignal, obtaining the BasicVector continuous state vector. However, this resulting vector, x_bar is always NaN. Out of desperation (and testing to make sure the rest of my program worked) I set x_bar to the controller's initialization cart_pole_context and have found that the simulation runs with a control signal of 0.0 (as expected). I can also set output to 100 and the cartpole simulation just flies off into endless space (as expected).
TL;DR: What is the proper way to obtain the continuous state vector in a custom controller extending LeafSystem with a DeclareVectorOutputPort?
Thank you for any help! I really appreciate it :) I've been teaching myself so it's been a little arduous haha.
# Combined Energy Shaping (SwingUp) and LQR (Balance) Controller
# with a simple state machine
class SwingUpAndBalanceController(LeafSystem):
def __init__(self, cart_pole, cart_pole_context, input_i, ouput_i, Q, R, x_star):
LeafSystem.__init__(self)
self.DeclareAbstractInputPort("state_input", AbstractValue.Make(FramePoseVector()))
self.DeclareVectorOutputPort("control_signal", BasicVector(1),
self.OutputControlSignal)
(self.K, self.S) = BalancingLQRCtrlr(cart_pole, cart_pole_context,
input_i, ouput_i, Q, R, x_star).get_LQR_matrices()
(self.A, self.B, self.C, self.D) = BalancingLQRCtrlr(cart_pole, cart_pole_context,
input_i, ouput_i,
Q, R, x_star).get_lin_matrices()
self.energy_shaping = EnergyShapingCtrlr(cart_pole, x_star)
self.energy_shaping_context = self.energy_shaping.CreateDefaultContext()
self.cart_pole_context = cart_pole_context
def OutputControlSignal(self, context, output):
#xbar = copy(self.cart_pole_context.get_continuous_state_vector())
xbar = copy(context.get_continuous_state_vector())
xbar_ = np.array([xbar[0], xbar[1], xbar[2], xbar[3]])
xbar_[1] = wrap_to(xbar_[1], 0, 2.0*np.pi) - np.pi
# If x'Sx <= 2, then use LQR ctrlr. Cost-to-go J_star = x^T * S * x
threshold = np.array([2.0])
if (xbar_.dot(self.S.dot(xbar_)) < 2.0):
#output[:] = -self.K.dot(xbar_) # u = -Kx
output.set_value(-self.K.dot(xbar_))
else:
self.energy_shaping.get_input_port(0).FixValue(self.energy_shaping_context,
self.cart_pole_context.get_continuous_state_vector())
output_val = self.energy_shaping.get_output_port(0).Eval(self.energy_shaping_context)
output.set_value(output_val)
print(output)
Here are two things that might help:
If you want to get the state of the cart-pole from MultibodyPlant, you probably want to be connecting to the continuous_state output port, which gives you a normal vector instead of the abstract-type FramePoseVector. In that case, your call to get_input_port().Eval(context) should work just fine.
If you do really want to read the FramePoseVector, then you have to evaluate the input port slightly differently. You can find an example of that here.
I made a model using BERT, for a NLI problem, the algorithm ran without problems, however, when I wanted to adapt it to RoBERTa, and I use strategy.scope (), it generates an error that I don't know how to solve, I appreciate any indication.
´´´
max_len1 = 515 # 128*4 de premisa mas 128*4 de hipotesis
def build_model1():
input_word_ids = tf.keras.Input(shape=(max_len1,), dtype=tf.int32,name="input_word_ids")
input_mask = tf.keras.Input(shape = (max_len1,),dtype=tf.int32,name = "input_mask")
input_type_ids = tf.keras.Input(shape = (max_len1,),dtype=tf.int32,name="input_type_ids")
embedding = model([input_word_ids,input_mask,input_type_ids])[0]
output = tf.keras.layers.Dense(3,activation='softmax')(embedding[:,0,:])
model3 = tf.keras.Model(inputs=[input_word_ids, input_mask, input_type_ids], outputs=output)
model3.compile(tf.keras.optimizers.Adam(lr=1e-5),
loss = 'sparse_categorical_crossentropy', metrics= ['accuracy'])
return model3
with strategy.scope():
model3 = build_model1()
model3.summary()
WARNING:tensorflow:The parameters `output_attentions`, `output_hidden_states` and `use_cache` cannot be updated when calling a model.They have to be set to True/False in the config object (i.e.: `config=XConfig.from_pretrained('name', output_attentions=True)`).
WARNING:tensorflow:AutoGraph could not transform <bound method Socket.send of <zmq.sugar.socket.Socket object at 0x7f2425631d00>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module, class, method, function, traceback, frame, or code object was expected, got cython_function_or_method
To silence this warning, decorate the function with #tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <bound method Socket.send of <zmq.sugar.socket.Socket object at 0x7f2425631d00>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module, class, method, function, traceback, frame, or code object was expected, got cython_function_or_method
To silence this warning, decorate the function with #tf.autograph.experimental.do_not_convert
WARNING: AutoGraph could not transform <bound method Socket.send of <zmq.sugar.socket.Socket object at 0x7f2425631d00>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module, class, method, function, traceback, frame, or code object was expected, got cython_function_or_method
To silence this warning, decorate the function with #tf.autograph.experimental.do_not_convert
WARNING:tensorflow:The parameters `output_attentions`, `output_hidden_states` and `use_cache` cannot be updated when calling a model.They have to be set to True/False in the config object (i.e.: `config=XConfig.from_pretrained('name', output_attentions=True)`).
WARNING:tensorflow:AutoGraph could not transform <function wrap at 0x7f243c214d40> and will run it as-is.
Cause: while/else statement not yet supported
To silence this warning, decorate the function with #tf.autograph.experimental.do_not_convert
WARNING:tensorflow:AutoGraph could not transform <function wrap at 0x7f243c214d40> and will run it as-is.
Cause: while/else statement not yet supported
To silence this warning, decorate the function with #tf.autograph.experimental.do_not_convert
WARNING:tensorflow:The parameter `return_dict` cannot be set in graph mode and will always be set to `True`.
WARNING: AutoGraph could not transform <function wrap at 0x7f243c214d40> and will run it as-is.
Cause: while/else statement not yet supported
To silence this warning, decorate the function with #tf.autograph.experimental.do_not_convert
WARNING:tensorflow:The parameter `return_dict` cannot be set in graph mode and will always be set to `True`.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-24-e91a2e7e4b41> in <module>()
1 with strategy.scope():
----> 2 model3 = build_model1()
3 model3.summary()
2 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py in _validate_compile(self, optimizer, metrics, **kwargs)
2533 'with strategy.scope():\n'
2534 ' model=_create_model()\n'
-> 2535 ' model.compile(...)' % (v, strategy))
2536
2537 # Model metrics must be created in the same distribution strategy scope
ValueError: Variable (<tf.Variable 'tfxlm_roberta_model/roberta/encoder/layer_._0/attention/self/query/kernel:0' shape=(1024, 1024) dtype=float32, numpy=
array([[-0.00294119, -0.00129846, 0.00517603, ..., 0.03835522,
0.0218797 , 0.02100084],
[-0.00933813, -0.05062149, 0.01634834, ..., -0.02387142,
0.0113477 , -0.02262339],
[-0.02023344, -0.04181184, -0.00581416, ..., -0.00609464,
0.00801133, 0.00512151],
...,
[-0.02129102, -0.03157991, -0.04071935, ..., 0.04682101,
0.01948426, 0.00312433],
[-0.04902648, -0.01055507, 0.01377375, ..., 0.00845209,
0.01616496, -0.01041171],
[ 0.00759454, -0.00162496, -0.00215843, ..., -0.03199947,
-0.03871808, 0.04949447]], dtype=float32)>) was not created in the distribution strategy scope
of (<tensorflow.python.distribute.tpu_strategy.TPUStrategy object at 0x7f21fcbbb210>). It is most
likely due to not all layers or the model or optimizer being created outside the distribution
strategy scope. Try to make sure your code looks similar to the following.
with strategy.scope():
model=_create_model()
model.compile(...)
´´´
The same code, as I said above, works perfectly for BERT, obviously, for RoBERTa I made the changes in the tokenizer and the loading of the model
I managed to solve it, investigating, I reached that the implementation of roberta went beyond just calling the model
Is there a way to assign a different base_address to the sub_blocks of a sub_block?
I have a case where I have something like this:
dut.rb:
sub_block ipBlock base_address: 0x11000000
and so the registers at this level all start with 0x110000000
But ipBlock also has its own sub_blocks:
ipblock.rb:
sub_block subIPBlock base_address: 0x0
with its own registers that due to an interface difference require a 0 base_address.
Unfortunately, when I add registers to subIPBlock they still have the base address of the top-level ipBlock:
sub_ipblock.rb:
add_reg :reg0, 0x0, 16, reset: 0xFFFF ...
Is there is a way to easily reassign the base address of the sub_block of a sub_block?
I believe you can use sub-block domains to achieve what you want.
sub_block :subx2, class_name: "SubX", base_address: { ips: 0x2000_0000, ahb: 0x3000_0000 }
dut.subx1.reg1.address(domain: :ips) # => 0x2000_0200
dut.subx1.reg1.address(domain: :ahb) # => 0x3000_0200
regards
In addition to the other answer, also note that reg.offset will return the block relative address, which it sounds like you want here.
All Origen drivers should override the register's address when an :address option is given, so within your model you could implement a read/write register method to add an :address option:
def write_register(reg, options = {})
if your_criteria_to_use_local_address
options[:address] = reg.offset
end
dut.write_register(reg, options) # Handover for original write
end
You could also force/override the base address within your model by implementing the following method:
def reg_base_address(options = {})
0
end
Finally, note that when using the domains per #rchitect-of-info's answer, you can define two domains when you instantiate a parent sub-block, then when you instantiate a child of that sub-block you can pick which of the available domains it is assigned to.
See this example from the documentation linked to in the other answer:
$dut.subx2.suby1.reg1.address # => 0x2000_0300
$dut.subx2.suby2.reg1.address # => 0x3000_0300
I need to compose a simple rmarkdown file, with text, code and the results of executed code included in a resulting PDF file. I would prefer if the source file is executable and self sifficient, voiding the need for a makefile.
This is the best I have been able to achieve, and it is far from good:
#!/usr/bin/env Rscript
library(knitr)
pandoc('hw_ch4.rmd', format='latex')
# TODO: how to NOT print the above commands to the resulting .pdf?
# TODO: how to avoid putting everyting from here on in ""s?
# TODO: how to avoid mentioning the file name above?
# TODO: how to render special symbols, such as tilde, miu, sigma?
# Unicode character (U+3BC) not set up for use with LaTeX.
# See the inputenc package documentation for explanation.
# nano hw_ch4.rmd && ./hw_ch4.rmd && evince hw_ch4.pdf
"
4E1. In the model definition below, which line is the likelihood?
A: y_i is the likelihood, based on the expectation and deviation.
4M1. For the model definition below, simulate observed heights from the prior (not the posterior).
A:
```{r}
points <- 10
rnorm(points, mean=rnorm(points, 0, 10), sd=runif(points, 0, 10))
```
4M3. Translate the map model formula below into a mathematical model definition.
A:
```{r}
flist <- alist(
y tilda dnorm( mu , sigma ),
miu tilda dnorm( 0 , 10 ),
sigma tilda dunif( 0 , 10 )
)
```
"
Result:
What I eventually came to use is the following header. At first it sounded neat, but later I realized
+ is indeed easy to compile in one step
- this is code duplication
- mixing executable script and presentation data in one file is a security risk.
Code:
#!/usr/bin/env Rscript
#<!---
library(rmarkdown)
argv <- commandArgs(trailingOnly=FALSE)
fname <- sub("--file=", "", argv[grep("--file=", argv)])
render(fname, output_format="pdf_document")
quit(status=0)
#-->
---
title:
author:
date: "compiled on: `r Sys.time()`"
---
The quit() line is supposed to guarantee that the rest of the file is treated as data. The <!--- and --> comments are to render the executable code as comments in the data interpretation. They are, in turn, hidden by the #s from the shell.
I'm trying to tweak this HaxeFlixel tutorial in order to make it more interesting and learn how to make games in the process. One of the first things I'm doing is restricting movement to tiles.
However, I've come to a wall – none of what I've tried is working. I've replaced the content of the movement() function in the Player class (which, for reference, is called every update()) with this:
if (FlxG.mouse.justReleased) {
var _path:FlxPath;
_path = new FlxPath(this, Reg.mWalls.findPath(getGraphicMidpoint(), FlxG.mouse.getWorldPosition()), speed);
}
(Reg.mWalls is where I moved PlayState._mWalls to make it accessible to this code.)
According to the docs this should create a FlxPath and immediately start it going (as the first argument isn't null), but instead it generates this error:
Null Object Reference
Called from openfl._v2.display.Stage.__pollTimers (openfl/_v2/display/Stage.hx line 1020)
Called from openfl._v2.display.Stage.__checkRender (openfl/_v2/display/Stage.hx line 317)
Called from openfl._v2.display.Stage.__render (openfl/_v2/display/Stage.hx line 1035)
Called from openfl._v2.display.DisplayObjectContainer.__broadcast (openfl/_v2/display/DisplayObjectContainer.hx line 280)
Called from openfl._v2.display.DisplayObject.__broadcast (openfl/_v2/display/DisplayObject.hx line 174)
Called from openfl._v2.display.DisplayObject.__dispatchEvent (openfl/_v2/display/DisplayObject.hx line 195)
Called from openfl._v2.events.EventDispatcher.dispatchEvent (openfl/_v2/events/EventDispatcher.hx line 100)
Called from openfl._v2.events.Listener.dispatchEvent (openfl/_v2/events/EventDispatcher.hx line 270)
Called from flixel.FlxGame.onEnterFrame (flixel/FlxGame.hx line 493)
Called from flixel.FlxGame.step (flixel/FlxGame.hx line 648)
Called from flixel.FlxGame.update (flixel/FlxGame.hx line 700)
Called from flixel.FlxState.tryUpdate (flixel/FlxState.hx line 155)
Called from PlayState.update (PlayState.hx line 125)
Called from flixel.group.FlxTypedGroup.update (flixel/group/FlxTypedGroup.hx line 89)
Called from Player.update (Player.hx line 47)
Called from Player.movement (Player.hx line 59)
Called from flixel.tile.FlxTilemap.findPath (flixel/tile/FlxTilemap.hx line 794)
Called from flixel.tile.FlxTilemap.computePathDistance (flixel/tile/FlxTilemap.hx line 1802)
Called from *._Function_1_1 (openfl/_v2/display/Stage.hx line 124)
AL lib: (EE) alc_cleanup: 1 device not closed
I ended up fixing this problem myself.
It turns out that I hadn't set any collision data for tile 0 (the blank tile) and that my map was full of spots that had no tile at all since they were 'outside'.
The fix was to flood-fill the empty area with tile 0 and add this to PlayState.create():
Reg.mWalls.setTileProperties(0, FlxObject.ANY);