In Python, I can select even or odd bits like this:
>>> bits = ['a','b','c','d'];
>>> bits[0::2]
['a', 'c']
>>> bits[1::2]
['b', 'd']
It would be very practical if I could do this in Verilog, so that I wouldn't have to expand the expression and do it manually. Expanded (i.e. {a[0], a[2]} and {a[1], a[3]}), it obviously wouldn't work with my otherwise parameterized wire set.
There is no mechanism in Verilog or SystemVerilog to do a bit slice like the Python example you gave. That is, you cannot specify a step of 2 between bits.
You can do this with a for-loop, and it doesn't need to be in a generate block like in your own answer.
Modified example from your answer:
always #(*) begin
for (int i = 0; i < FLOORS; i++) begin
RELEVANT[i] <= FLOOR_REQUEST[i*2+FORWARD];
end
end
This should synthesize okay as long as FLOORS is a constant.
It can be done with a generate block. Example:
wire [FLOORS-1:0] RELEVANT;
genvar i;
generate
for (i=0; i<FLOORS; i=i+1) begin
assign RELEVANT[i] = FLOOR_REQUEST[i*2+FORWARD];
end
endgenerate
FLOORS is the width of the output wire (half the width of the input wire).
RELEVANT is the result.
FORWARD is the even/odd selector (0 or 1).
FLOOR_REQUEST is the input.
Related
Goal: perform rolling window calculations on panel data in Stata with variables PanelVar, TimeVar, and Var1, where the window can change within a loop over different window sizes.
Problem: no access to SSC for the packages that would take care of this (like rangestat)
I know that
by PanelVar: gen Var1_1 = Var1[_n]
produces a copy of Var1 in Var1_1. So I thought it would make sense to try
by PanelVar: gen Var1SumLag = sum(Var1[(_n-3)/_n])
to produce a rolling window calculation for _n-3 to _n for the whole variable. But it fails to produce the results I want, it just produces zeros.
You could use sum(Var1) - sum(Var1[_n-3]), but I also want to be able to make the rolling window left justified (summing future observations) as well as right justified (summing past observations).
Essentially I would like to replicate Python's ".rolling().agg()" functionality.
In Stata _n is the index of the current observation. The expression (_n - 3) / _n yields -2 when _n is 1 and increases slowly with _n but is always less than 1. As a subscript applied to extract values from observations of a variable it always yields missing values given an extra rule that Stata rounds down expressions so supplied. Hence it reduces to -2, -1 or 0: in each case it yields missing values when given as a subscript. Experiment will show you that given any numeric variable say numvar references to numvar[-2] or numvar[-1] or numvar[0] all yield missing values. Otherwise put, you seem to be hoping that the / yields a set of subscripts that return a sequence you can sum over, but that is a long way from what Stata will do in that context: the / is just interpreted as division. (The running sum of missings is always returned as 0, which is an expression of missings being ignored in that calculation: just as 2 + 3 + . + 4 is returned as 9 so also . + . + . + . is returned as 0.)
A fairly general way to do what you want is to use time series operators, and this is strongly preferable to subscripts as (1) doing the right thing with gaps (2) automatically working for panels too. Thus after a tsset or xtset
L0.numvar + L1.numvar + L2.numvar + L3.numvar
yields the sum of the current value and the three previous and
L0.numvar + F1.numvar + F2.numvar + F3.numvar
yields the sum of the current value and the three next. If any of these terms is missing, the sum will be too; a work-around for that is to return say
cond(missing(L3.numvar), 0, L3.numvar)
More general code will require some kind of loop.
Given a desire to loop over lags (negative) and leads (positive) some code might look like this, given a range of subscripts as local macros i <= j
* example i and j
local i = -3
local j = 0
gen double wanted = 0
forval k = `i'/`j' {
if `k' < 0 {
local k1 = -(`k')
replace wanted = wanted + L`k1'.numvar
}
else replace wanted = wanted + F`k'.numvar
}
Alternatively, use Mata.
EDIT There's a simpler method, to use tssmooth ma to get moving averages and then multiply up by the number of terms.
tssmooth ma wanted1=numvar, w(3 1)
tssmooth ma wanted2=numvar, w(0 1 3)
replace wanted1 = 4 * wanted1
replace wanted2 = 4 * wanted2
Note that in contrast to the method above tssmooth ma uses whatever is available at the beginning and end of each panel. So, the first moving average, the average of the first value and the three previous, is returned as just the first value at the beginning of each panel (when the three previous values are unknown).
The idea of this project was to create an array of characters with numbers like this.
char some_numbers[] = {'0', '1', '2', '3', '4', '5'};
I made an integer of the size of that array right below that with.
int array_size = sizeof(some_numbers) / sizeof(*some_numbers);
What I wanted to try out was a simple iteration where instead of going through each iteration to show characters, I simply wanted to just type promote within the for loop to show a true integer. For example, I know that if you changed some_numbers[0] to an integer, you will get a value of 48. I used just this very idea of type promotion inside the for loop parameters that I created like this.
for (int i = int(some_numbers[0]); i <= int(some_numbers[array_size]); ++i)
What I did next was simply just have the body of this for loop execute a simple arithmetic expression to show a real integer value. This is the whole thing I typed out.
for (int i = int(some_numbers[0]); i <= int(some_numbers[array_size]); ++i)
{
std::cout << int(some_numbers[i]) - int(some_numbers[0]) << std::endl;
}
The whole thing that I wanted as an output was 0 1 2 3 4 5 but I'm just not getting anything. Where and what went wrong? How exactly should I shift my approach in the first place to get the output in the correct way for the correct data type I want?
I am looking to evaluate the sum an infinite geometric series in SymPy, and want to use the fact that I know the sum has to converge. (Similar to this post: How to Sum with conditions on Sympy?)
My code:
import sympy as sp
from sympy import oo
from sympy.assumptions import assuming, Q
from sympy.assumptions.assume import global_assumptions
x,k = sp.symbols('x k')
#global_assumptions.add(Q.is_true(sp.Abs(x)<1))
with assuming(Q.is_true(sp.Abs(x)<1)):
y = sp.Sum(x**k,(k,0,oo)).doit()
print y
The result is:
Piecewise((1/(-x + 1), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
So it seems the assumption that abs(x)<1 is not taken into account.
Using the global_assumptions (commented out here) does not give the desired result.
Concretely, how do I evaluate the sum such that the result would be 1/(1-x)?
At present, the assumptions made by the assumptions module are not used by the rest of SymPy modules, which makes them less useful than one might hope.
You can sort of fake it by using .subs like this:
y = sp.Sum(x**k, (k,0,oo)).doit().subs(sp.Abs(x) < 1, True)
which returns 1/(-x + 1).
I think this is the best one can do at present. Because this is just a literal substitution of True for a condition, rather than a logical inference, it won't work when the assumption doesn't exactly match a condition in Piecewise:
y = sp.Sum(x**k, (k,0,oo)).doit().subs(sp.Abs(x) < 1/2, True) # alas :(
So I have a String of integers that looks like "82389235", but I wanted to iterate through it to add each number individually to a MutableList. However, when I go about it the way I think it would be handled:
var text = "82389235"
for (num in text) numbers.add(num.toInt())
This adds numbers completely unrelated to the string to the list. Yet, if I use println to output it to the console it iterates through the string perfectly fine.
How do I properly convert a Char to an Int?
That's because num is a Char, i.e. the resulting values are the ascii value of that char.
This will do the trick:
val txt = "82389235"
val numbers = txt.map { it.toString().toInt() }
The map could be further simplified:
map(Character::getNumericValue)
The variable num is of type Char. Calling toInt() on this returns its ASCII code, and that's what you're appending to the list.
If you want to append the numerical value, you can just subtract the ASCII code of 0 from each digit:
numbers.add(num.toInt() - '0'.toInt())
Which is a bit nicer like this:
val zeroAscii = '0'.toInt()
for(num in text) {
numbers.add(num.toInt() - zeroAscii)
}
This works with a map operation too, so that you don't have to create a MutableList at all:
val zeroAscii = '0'.toInt()
val numbers = text.map { it.toInt() - zeroAscii }
Alternatively, you could convert each character individually to a String, since String.toInt() actually parses the number - this seems a bit wasteful in terms of the objects created though:
numbers.add(num.toString().toInt())
On JVM there is efficient java.lang.Character.getNumericValue() available:
val numbers: List<Int> = "82389235".map(Character::getNumericValue)
Since Kotlin 1.5, there's a built-in function Char.digitToInt(): Int:
println('5'.digitToInt()) // 5 (int)
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/digit-to-int.html
For clarity, the zeroAscii answer can be simplified to
val numbers = txt.map { it - '0' }
as Char - Char -> Int. If you are looking to minimize the number of characters typed, that is the shortest answer I know. The
val numbers = txt.map(Character::getNumericValue)
may be the clearest answer, though, as it does not require the reader to know anything about the low-level details of ASCII codes. The toString().toInt() option requires the least knowledge of ASCII or Kotlin but is a bit weird and may be most puzzling to the readers of your code (though it was the thing I used to solve a bug before investigating if there really wasn't a better way!)
I am trying to evaluate a certain expression under consideration of assumption. Specifically my problem is related to indexedBase objects.
See the following code:
from sympy import *
init_printing(use_latex="mathjax")
ntot = symbols("n_tot", integer = True)
i = Idx("i",(1,ntot))
k = Idx("k", (1,ntot))
j = Idx("j",(1,ntot))
x = IndexedBase("x")
As an example let's take the derivative of two summations over x[i].
expr = Sum(Sum(x[i],(i,1,ntot)),(k,1,ntot)).diff(x[j])
(NOTE: this is not possible in the current SymPy version 1.0, it is possible with the development version and will be available in future SymPy stable versions.)
I want to evaluate the expression and get a piecewise answer:
print(expr.doit())
OUTPUT: n_tot*Piecewise((1, And(1 <= j, j <= n_tot)), (0, True))
So my problem is, how can I tell sympy that I know for certain that j is between 1 and ntot. So that my result is 1:
I tried the following but with no luck:
with assuming(j==2):
expr=Sum(Sum(x[i],(i,1,ntot)),(k,1,ntot)).diff(x[j]).doit()
Assumptions on inequalities are a sorely missed feature in SymPy.
Technically the Idx object was created to allow a symbol to contain a definition range, so as to put limits on indexed symbols. Your j already has this information:
In [28]: j.upper
Out[28]: n_tot
In [29]: j.lower
Out[29]: 1
Unfortunately, the inequality class is not meant to handle Idx objects, so its range gets disregared.
You could actually try:
In [32]: simplify(expr.doit()).args[0][0]
Out[32]: n_tot
This manually extracts the first term of the Piecewise expression.
Obviously, the current algorithm needs improvement, it should already tell to Sum that j is within the correct range in order to give 1 as a result.