Inner constructor in Julia - object

I am moving from using Python to Julia and would like to create an object like this:
class myObject():
def __init__(inputA,inputB):
self.x = inputA;
self.y = inputB;
self.z = x*y;
I know that in Julia we use struct but am unsure how to implement the functionality as describe above without setting z manually (outside of the inner-constructor). How would I do this?

You can do it either as an inner constructor:
struct A
x::Int
y::Int
z::Int
# Inner constructor
A(x, y) = new(x, y, x*y)
end
or an outer constructor:
struct B
x::Int
y::Int
z::Int
end
# Outer constructor
B(x, y) = B(x, y, x*y)
Everything should be covered in the Constructors section of the manual.

Related

Sympy - Find all expressions of a certain level

in the documentation it is shown, how one can use srepr(expr) to create a string containing all elements of the formula tree.
I would like to have all elements of a certain level of such a tree in a list, not as a string but as sympy objects.
For the example
from sympy import *
x,y,z = symbols('x y z')
expr = sin(x*y)/2 - x**2 + 1/y
s(repr)
"""
gives out
=> "Add(Mul(Integer(-1), Pow(Symbol('x'), Integer(2))), Mul(Rational(1, 2),
sin(Mul(Symbol('x'), Symbol('y')))), Pow(Symbol('y'), Integer(-1)))"
"""
This should lead to
first_level = [sin(x*y)/2,-x**2,1/y]
second_level[0] = [sin(x*y),2]
I assume, the fundamental question is, how to index a sympy expression according to the expression tree such that all higher levels starting from an arbitrary point are sumarized in a list element.
For the first level, it is possible to solve the task
by getting the type of the first level (Add in this case and then run)
print(list(Add.make_args(expr)))
but how does it work for expressions deeper in the tree?
I think the thing you are looking for is .args. For example your example we have:
from sympy import *
x, y, z = symbols('x y z')
expr = sin(x * y) / 2 - x ** 2 + 1 / y
first_level = expr.args
second_level = [e.args for e in first_level]
print(first_level)
print(second_level[0])
"""
(1/y, sin(x*y)/2, -x**2)
(y, -1)
"""
These give tuples, but I trust that you can convert them to lists no problem.
If you want to get directly to the bottom of the tree, use .atoms() which produces a set:
print(expr.atoms())
"""
{x, 2, y, -1, 1/2}
"""
Another thing that seems interesting is perorder_traversal() which seems to give a tree kind of object and if you iterate through it, you get something like a power set:
print([e for e in preorder_traversal(expr)])
"""
[-x**2 + sin(x*y)/2 + 1/y, 1/y, y, -1, sin(x*y)/2, 1/2, sin(x*y), x*y, x, y, -x**2, -1, x**2, x, 2]
"""
Here is the beginning of the docstring of the function:
Do a pre-order traversal of a tree.
This iterator recursively yields nodes that it has visited in a pre-order fashion. That is, it yields the current node then descends through the tree breadth-first to yield all of a node's children's pre-order traversal.
For an expression, the order of the traversal depends on the order of .args, which in many cases can be arbitrary.
If any of these are not what you want then I probably don't understand your question correctly. Apologies for that.

How to create a SOC constraints with different Variable vectors's element

I am working on an optimization problem with cvxpy. And I need to create a SOC(second order cone) constraint.
The way described in cvxpy documents is like following:
We use cp.SOC(t, x) to create the SOC constraint ||x||_2 <= t.
where t is the scalar part of the second-order constraint, x is a matrix whose rows/columns are each a cone.
Here is the standard way how cvxpy solve a SOCP problem.
But now i need to extract Variable from different places.
import cvxpy as cvx
Y = cvx.Variable(3)
Z = cvx.Variable(3)
T = cvx.Variable(3)
soc_constraints = []
for in range(3):
t = T[i]
x = np.matrix([Y[i], Z[i]])
soc_constraints += [cvx.SOC(t, x)]
But I get one error here.
AttributeError: 'matrix' object has no attribute 'variables'
I suppose x should be a cvxpy expression. But how can i create a SOC constraint out of different Variable vectors.
Some help would be appreciated.

Little puzzle on functional programming in Python

The input is two integers in one line, x and y. I need to write a basically one-line program which does different things with x and y, and prints the result. Say, the output should be x + 1, y * y. Or list(range(x)), y // 2. Whatever operations but different. No def functions, also 'if' and 'for' are prohibited. As far as i understand, should look something like:
print(
*map(
lambda x: ??? ,
map(
int, input().split()
)
)
)
(But lambda can only do same thing to both inputs, right? )
I know it is possible and i've been thinking about this for three days to no avail. Most probable i miss something very obvious.
Your lambda function can take an x and y and turn them into pretty much any expression. Then you would call that function, doing the processing of the inputs outside of that lambda
print(*(lambda x, y: (x+1, y*y))(*map(int, input().split())))
print(*(lambda x, y: (list(range(x)), y//2))(*map(int, input().split())))
This seems to work just fine:
print(
*(lambda x: [int(x[0]) + 1, int(x[1]) * int(x[1])])(
input().split()
)
)
No fancy functional tricks or map are needed.

tensorflow: creating variables in fn of tf.map_fn returns value error

I have questions regarding variable initialization in map_fn.
I was trying to apply some highway layers separately on each individual element in a tensor, so i figure map_fn might be the best way to do it.
segment_list = tf.reshape(raw_segment_embedding,[batch_size*seqlen,embed_dim])
segment_embedding = tf.map_fn(lambda x: stack_highways(x, hparams), segment_list)
Now the problem is my fn, i.e. stack_highways, create variables, and for some reason tensorflow fails to initialize those variables and give this error.
W = tf.Variable(tf.truncated_normal(W_shape, stddev=0.1), name='weight')
ValueError: Initializer for variable body/model/parallel_0/body/map/while/highway_layer0/weight/ is from inside a control-flow construct, such as a loop or conditional. When creating a variable inside a loop or conditional, use a lambda as the initializer.
I am pretty clueless now, based on the error I suppose it is not about scope but I have no idea how to use a lambda as the initializer (I dont even know what exactly does that mean).
Below are the implementation of stack_highways, any advice would be much appreciated..
def weight_bias(W_shape, b_shape, bias_init=0.1):
"""Fully connected highway layer adopted from
https://github.com/fomorians/highway-fcn/blob/master/main.py
"""
W = tf.Variable(tf.truncated_normal(W_shape, stddev=0.1), name='weight')
b = tf.Variable(tf.constant(bias_init, shape=b_shape), name='bias')
return W, b
def highway_layer(x, size, activation, carry_bias=-1.0):
"""Fully connected highway layer adopted from
https://github.com/fomorians/highway-fcn/blob/master/main.py
"""
W, b = weight_bias([size, size], [size])
with tf.name_scope('transform_gate'):
W_T, b_T = weight_bias([size, size], bias_init=carry_bias)
H = activation(tf.matmul(x, W) + b, name='activation')
T = tf.sigmoid(tf.matmul(x, W_T) + b_T, name='transform_gate')
C = tf.sub(1.0, T, name="carry_gate")
y = tf.add(tf.mul(H, T), tf.mul(x, C), name='y') # y = (H * T) + (x * C)
return y
def stack_highways(x, hparams):
"""Create highway networks, this would not create
a padding layer in the bottom and the top, it would
just be layers of highways.
Args:
x: a raw_segment_embedding
hparams: run hyperparameters
Returns:
y: a segment_embedding
"""
highway_size = hparams.highway_size
activation = hparams.highway_activation #tf.nn.relu
carry_bias_init = hparams.highway_carry_bias
prev_y = None
y = None
for i in range(highway_size):
with tf.name_scope("highway_layer{}".format(i)) as scope:
if i == 0: # first, input layer
prev_y = highway_layer(x, highway_size, activation, carry_bias=carry_bias_init)
elif i == highways - 1: # last, output layer
y = highway_layer(prev_y, highway_size, activation, carry_bias=carry_bias_init)
else: # hidden layers
prev_y = highway_layer(prev_y, highway_size, activation, carry_bias=carry_bias_init)
return y
Warmest Regards,
Colman
TensorFlow provides two main ways of initializing variables:
"lambda" initializers: callables that return the value of initialization. TF provides many nicely packaged ones.
Initialization by tensor values: This is what you are using currently.
The error message is stating that you need to use the first type of initializer when using variables from within a while_loop (which map_fn calls internally). (In general lambda initializers seem more robust to me.)
Additionally in the past, tf.get_variable seems to be preferred over tf.Variable when used from within control flow.
So, I suspect you can resolve your issue by fixing your weight_bias function to something like this:
def weight_bias(W_shape, b_shape, bias_init=0.1):
"""Fully connected highway layer adopted from
https://github.com/fomorians/highway-fcn/blob/master/main.py
"""
W = tf.get_variable("weight", shape=W_shape,
initializer=tf.truncated_normal_initializer(stddev=0.1))
b = tf.get_variable("bias", shape=b_shape,
initializer=tf.constant_inititializer(bias_init))
return W, b
Hope that helps!

Define swizzling programmatically (as in GLSL)

How would one write swizzling as a defined behaviour in a programming language? (swizzling members like matrices and vectors in GLSL) So if I wanted to make a programming language that would allow the definition of swizzling on some members, what would be a good way to do it? So for example I could do this:
struct
{
swizzable
{
float x, float y, float z, float w
}
}
But this is missing a lot. For example it does not define that what sould it return when I swizzle more or less elements or assign to a subset or just the elements backwards. Like in GLSL I can do v.xyz to create a Vec3 from a Vec4 called v. Or I could assign a subset of members: v.zyx = ... in any order.
So this swizzable substruct is not a solution (or at least too limited). Another way would be to return an array of swizzled members and an implicit cast (with a constructor) would generate the wanted element:
struct Vec2
{
swizzable { float x, float y }
Vec2(float[2] elements)
{ x = elements[0]; y = elements[1]; }
}
struct Vec3
{
swizzable { float x, float y, float z }
}
So if I accessed a Vec3's x and y via swizzling, I would get a float[2] and because I have a constructor for Vec2, I can assign this array to it (and implicitly instantiating a vec2).
This looks like a better solution but still: How could one do better?
Edit: Sorry I didn't specify the question: I want to implement a programming language that supports this kind of thing.
I'm not sure how to give a good, detailed answer, so here is just one idea.
If I understand right, swizzling is mainly a syntactic convenience. The page https://www.opengl.org/wiki/GLSL_Optimizations gives the following example of swizzling:
gl_FragColor = mycolor.xyzw * constantList.xxxy + constantList.yyyx;
This could simply be syntactic shorthand for something like:
gl_FragColor = Vector(mycolor.x, mycolor.y, mycolor.z, mycolor.w)
* Vector(constantList.x, constantList.x, constantList.x, constantList.y)
+ Vector(constantList.y, constantList.y, constantList.y, constantList.x);
So, one step may be to figure out how to parse the shorter syntax and interpret it as meaning something similar to the longer syntax.
I don't see why it would be necessary to declare the struct as anything more complicated than struct myStruct { float x, float y, float z, float w }. The language itself should be able to handle all the details of how to implement this swizzling.

Resources