Error when trying to compile a zero-sized record variable in Dymola - modelica

I'm creating an array of records dependent on the number of port connections made in a component. The actual component works fine when the number of connections is 1 or more, but does not work when no connections are made. Looking for input on how to resolve or workaround.
Here is the error:
Below is a MWE:
model RecordIssue
record Record
Real a=1;
end Record;
parameter Integer nPorts=0 annotation (Dialog(connectorSizing=true));
Modelica.Fluid.Interfaces.FluidPorts_a ports_a[nPorts];
// declare record array instance for each port connection
parameter Record[nPorts] recordInstance={Record() for i in 1:nPorts};
// this next line is an issue only when nPorts = 0 or no connections made
Real test[:]=recordInstance[:].a;
end RecordIssue;
The expected/desired behavior would be for the variable test to not exist when nPorts=0, which is the normal behavior for something like Real test[:] = {1.0 for i in 1:nPorts};

A workaround would be to ensure that the record variable is never empty and avoid access when nPorts is zero.
model RecordIssue
record Record
Real a=1;
end Record;
record Dummy
extends Record(a=Modelica.Constants.inf);
end Dummy;
parameter Integer nPorts = 0 annotation (Dialog(connectorSizing=true));
Modelica.Fluid.Interfaces.FluidPorts_a ports_a[nPorts];
// declare record array and ensure that at least one exists
parameter Record[max(nPorts, 1)] recordInstance = if nPorts > 0 then {Record() for i in 1:nPorts} else {Dummy()};
// decide here if recordInstance shall be used
Real test[nPorts] = if nPorts > 0 then recordInstance[:].a else fill(0, 0);
end RecordIssue;

Related

Converting arrays from signed to integer in VHDL?

I have declared an array
type datastream is array(0 to 10) of signed (5 downto 0);
For simulation, I want to display the array as integer-numbers
So I created
type datastream_int is array(0 to 10) of integer;
and
signal DIN_ARRAY: datastream;
signal DIN_ARRAY_int: datastream_int;
...
DIN_ARRAY_real <= datastream_int(DIN_ARRAY);
But it fails. How to convert it? Dont want to use a for loop
The numeric_std package, that I assume you are using, provides a to_integer function to convert from a single signed value to a single integer object. For an array, you're going to have to use a for loop. Something like this:
for i in DIN_ARRAY'range loop
DIN_ARRAY_int <= to_integer(DIN_ARRAY(i));
end loop;
You could also provide a conversion function (it will also contain a for loop)
function datastream_to_datastream_int( d : datastream ) return datastream_int is
variable r : datastream_int;
begin
for i in d'range loop
r(i) := to_integer(d(i));
end loop;
return r;
end function;
....
--no loop required
DIN_ARRAY_int <= datastream_to_datastream_int(DIN_ARRAY);
So, there will be a for loop somewhere.
Your code fails because you have attempted a type conversion, which is only allowed between similar types - ie. array or record types where the element types match between the two types.
PS. VHDL 2008 provides an integer_vector type in the std.standard library (which is included by default) which may help by allowing you to do this:
signal DIN_ARRAY_int: integer_vector(DIN_ARRAY'range);
If you did decide to keep datastream_int as per your original, you could type convert it to an integer_vector, because the types are similar:
my_iv <= integer_vector(DIN_ARRAY_int);

Dynamic generation of signal spies in testbench

I have a .txt file that contains certain signals that I want to monitor in my testbench during the application of some stimulus.
I am creating an initial block in which I am reading the file and then I try to generate a init_signal_spy() for every one of the lines that I have read.
The code that I have written up until this point has the following format:
module testbench();
logic probes[];
initial begin : read_signals_to_dump_at
automatic int fd;
automatic string fname,line,line_stripped;
if ($value$plusargs("sigfile=%s",fname)) begin : read
fd = $fopen(fname,"r");
while($fgets(line,fd)) begin
//static logic net_to_be_probed;
automatic sig_and_spy entry = new();
// Trim away the '\n' from the line.
line_stripped = line.substr(0,line.len()-2);
// Resize the array
probes = new [probes.size() + 1] (probes);
// Link the extracted new line with the probe list
// - this raises an error "An invalid empty string was passed in as the Destination object."
// - expected since the last element is empty...
$init_signal_spy(line_stripped, probes[probes.size()-1] , 1);
end
end
end : read_signals_to_dump_at
endmodule
In the code above, just before I issue the generation for the spy, I get why the error
An invalid empty string was passed in as the Destination object.
is generated by the compiler. Although the array has been resized, it does not hold any element i.e., its empty. Thus, I tried creating locally a logic variable that then I assign to the signal spy within the loop in the following manner:
module testbench();
logic probes[];
initial begin : read_signals_to_dump_at
automatic int fd;
automatic string fname,line,line_stripped;
if ($value$plusargs("sigfile=%s",fname)) begin : read
fd = $fopen(fname,"r");
while($fgets(line,fd)) begin
logic new_probe;
// Trim away the '\n' from the line.
line_stripped = line.substr(0,line.len()-2);
// Resize the array and copy old values.
probes = new [probes.size() + 1] (probes);
// Add the new probe to the Testbenchs' probes array
probes[probes.size()-1] = new_probe;
// Again, An invalid empty string was passed in as the Destination object.
$init_signal_spy(line_stripped, probes[probes.size()-1] , 1);
end
end
end : read_signals_to_dump_at
endmodule
But then again, I see the same error at runtime during the simulation. So...Is there a way of achieving such a "dynamic" signal monitoring in the testbench somehow? As far as I understood the error concerns that the destination object is NOT a signal of the testbench. Thus the logic new_probe has no effect. Which is to be expected I mean, but is there a way of achieving the desired behavior in the Testbench via sysverilog?
You have at least two problems.
Both the source and destination arguments to init_signal_spy() need to be strings. Your destination argument is an integral variable with a 0 value, and that gets interpreted as a null string. init_signal_spy() was designed for mixed language simulation, and using strings was the only way to achieve that.
Your destination variable should be queue, not a dynamic array. Every time you re-size a dynamic array, the previous elements get relocated and that breaks the previous connection made by signal spy.
This example shows the proper syntax for string this up
module top;
int A[$];
int s1,s2;
initial begin
A.push_back(0);
$init_signal_spy("s1","A[0]");
A.push_back(0);
$init_signal_spy("s2","A[1]");
#1 s1 = 1;
#1 s2 = 2;
#1 $display("%p",A);
end
endmodule
A far better solution for performance is converting your .txt file into actual SystemVerilog code that can be compiled into your testbench.

System Verilog: randomization per instance at initial

I want to simulate a multiple latches with random starting conditions, but I want each instance to have its own initial condition
This is a simplified version of the code. I would like the value to be different in both of the instances, without changing the interface
module random_usage();
integer addr1;
real data;
initial begin
addr1 = $urandom();
data = $urandom();
$display("addr1=%0d, data=%0d",addr1,data);
end
endmodule
module tb();
integer seed = 1;
random_usage a();
random_usage b();
initial
begin
#5;
seed = $get_initial_random_seed();
$display("seed=%0d", seed);
end
endmodule
What I have seen so far:
Instance specific $urandom in system-verilog
solution doesn't work in initial condition, or even when you feed the same clock
https://www.systemverilog.io/randomization
I have modules, so i don't know how to apply the solutions, or even if it will work here
https://www.reddit.com/r/FPGA/comments/jd0dmu/system_verilog_force_randomization_different_per/
seems to be the same question, and there is no straight solution, but the last person gave a VCS flag. I am using VCS, but i have not been able to get the flag to work
The IEEE 1800-2017 SystemVerilog LRM section 18.14.1 Random stability properties says rather naively that each instances gets seeded with the same initialization seed.
Most tools now have a switch changing that behavior by using the hierarchical path name to seed each instance. Some tools have even made that the default. If you want tool independent behavior, you can use this package:
package seed_instance;
int initial_seed = $urandom;
function automatic void srandom(string path);
static int hash[int];
int hash_value = initial_seed;
process p = process::self();
for(int i=0;i<path.len();i++)
hash_value+=path[i]*(i*7);
if (!hash.exists(hash_value))
hash[hash_value] = hash_value;
else
hash[hash_value]+=$urandom; // next seed
p.srandom(hash[hash_value]);
endfunction
endpackage
module random_usage();
integer addr1;
real data;
initial begin
seed_instance::srandom($sformatf("%m"));
addr1 = $urandom();
data = $urandom();
$display("1: addr1=%0d, data=%0d",addr1,data);
end
initial begin
seed_instance::srandom($sformatf("%m"));
addr1 = $urandom();
data = $urandom();
$display("2: addr1=%0d, data=%0d",addr1,data);
end
endmodule
module tb();
integer seed = 1;
random_usage a();
random_usage b();
endmodule

Numerical values associated with Drop Down options

So I am creating an app to work out a value based on a series of variables. The variables are:
Gender
Age
Weight
Creatinine
Here's what the app looks like:
In order to simplify the process somewhat I decided to make the gender selection a dropdown menu, this has caused me some issues since I have it setup like so:
And the maths associated with the button looks like so:
function CalculateButtonPushed(app, event)
gender = app.PatientGenderDropDown.Value ;
age = app.PatientAgeEditField.Value ;
weight = app.LeanBodyWeightEditField.Value ;
serum = app.SerumCreatinineEditField.Value ;
final = (gender*(age)*weight) / (serum) ;
app.ResultEditField.Value = final ;
end
end
Running this gives the following error:
Error using
matlab.ui.control.internal.model.AbstractNumericComponent/set.Value
(line 104) 'Value' must be numeric, such as 10.
As far as I am aware, the values I input into ItemsData are numeric values. Have I missed something or is there a better way to do this?
If you put a breakpoint in the offending file on the appropriate line (by running the below code),
dbstop in uicomponents\+matlab\+ui\+control\+internal\+model\AbstractNumericComponent.m at 87
you could see the following in your workspace, after clicking the button:
There are two separate problems here, both of which can be identified by looking at the newValue validation code (appearing in AbstractNumericComponent.m):
% newValue should be a numeric value.
% NaN, Inf, empty are not accepted
validateattributes(...
newValue, ...
{'numeric'}, ...
{'scalar', 'real', 'nonempty'} ...
);
Here are the issues:
The new value is a vector of NaN.
The reason for this is in this line:
final = (gender*(age)*weight) / (serum) ;
where serum has a value of 0 - so this is the first thing you should take care of.
The new value is a vector of NaN.
This is a separate problem, since the set.Value function (which is implicitly called when you assign something into the Value field), is expecting a scalar. This happens because gender is a 1x4 char array - so it's treated as 4 separate numbers (i.e. the assumption about ItemsData being a numeric is incorrect). The simplest solution in this case would be to str2double it before use. Alternatively, store the data in another location
(such as a private attribute of the figure), making sure it's numeric.

SAS hash objects: multidata merge

I'm new to hash objects, but I'd like to learn more about them. I'm trying to find ways to substitute all possible proc sql and regular merges with hash whenever possible. While playing around with SASHELP datasets, I ran into the following issue:
Let's say I have a dataset of 10 unique observations (car manufacturer) and I want to match it up with another table that contains various models of these cars, so the car make repeats in that table. The other important aspect to note is that not all car makes are present in the table I'm looking up, but I still would like to retain those in my table.
Consider the code below:
proc sql noprint;
create table x as select distinct make
from sashelp.cars;
quit;
data x;
set x (obs = 10);
if make = "GMC" then make = "XYZ";
run;
data hx (drop = rc);
if 0 then set sashelp.cars(keep = make model);
if _n_ = 1 then do;
declare hash hhh(dataset: 'sashelp.cars(keep = make model)', multidata:'y');
hhh.DefineKey('make');
hhh.DefineData('model');
hhh.DefineDone();
end;
set x;
rc = hhh.find();
do while(rc = 0);
output;
rc = hhh.find_next();
end;
if rc ne 0 then do;
call missing(model);
output;
end;
run;
If all makes in table X were also in table cars, then removing output command after call missing(model) would do exactly what I want. But I also want to make sure that make "XYZ" will remain in the table.
The existing code, however, produces a blank after it find all matching models, like so:
make model
==========
Acura MDX
Acura RSX Type S 2dr
Acura TSX 4dr
... (skipping a few rows)
Acura NSX coupe 2dr manual S
Acura
Audi A4 1.8T 4dr
As you can see, in the above table, there is a missing model in the second to last row. This pattern appears in the end of every make.
Any suggestions on how to fix this would be highly appreciated!
Many thanks
The direct answer: you need to consider this section.
rc = hhh.find();
do while(rc = 0);
output;
rc = hhh.find_next();
end;
if rc ne 0 then do;
call missing(model);
output;
end;
What's happening here is you are repeatedly trying to find next, fine, until you fail. Okay. Now you're in rc ne 0 condition, though, even though you really mean that last step to only be used if you didn't even find one.
You can handle this a couple of ways. You can do this:
rc = hhh.find();
if rc ne 0 then do;
call missing(model);
output;
end;
else
do while(rc = 0);
output;
rc = hhh.find_next();
end;
Or, you can add a counter to the do while loop, and then execute the call missing/output if that counter stores a 0. The above is probably easier.
Further, you probably should consider whether a hash is the right solution for this problem. While it is possible to solve this with multidata hashes, keyed set is usually more efficient for something like this, and much easier to code.