What is the correct way to assign to a field of a GLKVector3 (or 4)?
This fails:
Which makes sense since .x and .z are getters. What is the workaround?
I believe that in Swift GLKVector3s are immutable, whether a var or a let. Use GLKVector3Make to create one with arbitrary Float values; subsequently generate new results to new instances.
So:
let ballLocation = GLKVector3Make(
(locationInBallCoordinates.x - ballCentre.x) / ballRadius,
0.0,
(locationInBallCoordinates.y - ballCentre.y) / ballRadius)
Or, if locationInBallCoordinates and ballCentre were already instances of GLKVector3 — and the y-to-z component switch that I hadn't noticed when I first wrote this answer weren't there — then:
let ballLocation =
GLKVector3DivideScalar(
GLKVector3Subtract(locationInBallCoordinates, ballCentre),
ballRadius)
It's probably easiest to unpack and repack to move ys into zs but you could also use a matrix multiply if you were desperate to keep it high level.
Related
I am trying to reimplement littledog.ipynb using C++. I find it is hard to translate the function velocity_dynamics_constraint and have 3 questions
What is the function of ad_velocity_dynamics_context? Can we ignore it?
How to reimplement velocity_dynamics_constraint using C++? Do I have to create a new class like class VelocityDynamicsConstraint : public drake::solvers::Constraint? Is three any easier way to implement it?
Why we need to consider isinstance(vars[0], AutoDiffXd) condition?
# Some code from https://github.com/RussTedrake/underactuated/blob/master/examples/littledog.ipynb
ad_velocity_dynamics_context = [
ad_plant.CreateDefaultContext() for i in range(N)
]
def velocity_dynamics_constraint(vars, context_index):
h, q, v, qn = np.split(vars, [1, 1+nq, 1+nq+nv])
if isinstance(vars[0], AutoDiffXd):
if not autoDiffArrayEqual(
q,
ad_plant.GetPositions(
ad_velocity_dynamics_context[context_index])):
ad_plant.SetPositions(
ad_velocity_dynamics_context[context_index], q)
v_from_qdot = ad_plant.MapQDotToVelocity(
ad_velocity_dynamics_context[context_index], (qn - q) / h)
else:
if not np.array_equal(q, plant.GetPositions(
context[context_index])):
plant.SetPositions(context[context_index], q)
v_from_qdot = plant.MapQDotToVelocity(context[context_index],
(qn - q) / h)
return v - v_from_qdot
for n in range(N-1):
prog.AddConstraint(partial(velocity_dynamics_constraint,
context_index=n),
lb=[0] * nv,
ub=[0] * nv,
vars=np.concatenate(
([h[n]], q[:, n], v[:, n], q[:, n + 1]))
What is the function of ad_velocity_dynamics_context? Can we ignore it?
The context caches the intermediate computation result for a given q, v, u. It is very common that several constraints are imposed on the same set of q, v, u (for example, consider at the final time, we typically have a kinematic constraint on the final state, say the robot foot has to land on the ground and its center of mass is at a certain location. At the same time we we have the velocity dynamics constraint on the final state). Hence these different constraints can share some intermediate computation result, such as the rigid transform between each adjacent links. Hence we cache the result in ad_velocity_dynamics_context, and this ad_velocity_dynamics_context can be used later when we impose other constraints.
How to reimplement velocity_dynamics_constraint using C++? Do I have to create a new class like class VelocityDynamicsConstraint : public drake::solvers::Constraint? Is there any easier way to implement it?
That is right, you will need to create a new class VelocityDynamicsConstraint. The main challenge in implementing this class is to write the three overloaded DoEval function for three scalar types (double, AutoDiffXd, symbolic::Expression). You can refer to PositionConstraint as a reference. And for the moment you can ignore the case to call DoEval(const Eigen::Ref<const AutoDiffXd>&, AutoDiffXd*) with a MultibodyPlant<double> case, and only implement the this DoEval function with MultibodyPlant<AutoDiffXd>.
Why we need to consider isinstance(vars[0], AutoDiffXd) condition?
Because when the scalar type is AutoDiffXd, we want to compare not only the value of q against the one stored in context, but also its gradient. If they are different, then we need to call SetPositions to recompute the cache. When the scalar type is double, we then only need to compare the value.
I'm not sure what the point of setting the metamethod of Stack to Stack is.
I've looked around but none of the explanations made too much sense. I get that sometimes instances may need to fall back on Stack for any missing methods but was hoping for a clearer explanation.
Stack = {}
Stack.__index = Stack
Let's say you have a "2d vector" "class" which has a .x and a .y. You write a dotproduct function for them:
function dotproduct(a, b)
return a.x * b.x + a.y * b.y
end
The simplest way to let you write foo:dot(bar) would be to put a .dot property on every new instance:
-- Make a "V2" namespace
local V2 = {}
function V2.new(x, y)
return {
x = x,
y = y,
-- Attach any methods to the object, also
dot = dotproduct,
}
end
However, as the number of methods grows, this gets worse for two reasons. One is that your objects get larger -- even though you only need to hold two numbers on each vector, most of the hashtable is functions which are always the same! Another is that multiple constructors get difficult because you need to duplicate the work in each constructor.
A solution to this is the __index metatable. Instead of copying each method onto each new object, you can just point to where to find "missing" methods as they needed:
V2.dot = dotproduct
function V2.new(x, y)
return setmetatable({x = x, y = y}, {__index = V2})
end
This design has a small drawback. First, you're allocating a new metatable in addition to every table, which is a waste of memory (all of the metatables are the same). Second, you don't have an opportunity to override other methods without growing this new metatable (the same annoyance from before).
So, we just make V2 be the single metatable:
V2.__index = V2
function V2.new(x, y)
return setmetatable({x = x, y = y}, V2)
end
I have some scientific project. There are vectors / square matrices of various lengths there. Obviously (for example) a vector of length 2 cannot be added to a vector of length 3 (and so on and so forth). There are several NET libraries, which deal with vectors / matrices. All of them either have generic vectors / matrices OR have some very specific vectors / matrices, which do not suite the needs.
Most, if not all, of these libraries can create a vector from a list or array. Unfortunately, If I mistakenly give an input array of the wrong length, then I will get a vector of the wrong length and then everything will blow up at run time!
I wonder if it is possible to check array length at compile time so that to get a compile error if, let’s say, I try to pass a 5-element array to a vector of length 2 “constructor”. After all, printfn does almost that!
F# type providers come to mind, but I am not sure how to apply them here.
Thanks a lot!
Thanks to the OP for an interesting question. My answer frequency has dropped not because of unwillingness to help but rather that there a few questions that tickles my interest.
We don't have dependent types in F# and F# doesn't support generics with numerical type arguments (like C++).
However we could create distinct types for different dimensions like Dim1, Dim2 and so on and provide them as type arguments.
This would allow us to have a type signature for apply that applies a vector a matrix like this:
let apply (m : Matrix<'R, 'C>) (v : Vector<'C>) : Vector<'R> = …
The code won't compile unless the columns of the matrix matches the length of the vector. In addition; the resulting vector has the length that is rows of the columns.
One way to do this is defining an interface IDimension and some concrete implementions representing the different dimensions.
type IDimension =
interface
abstract Size : int
end
type Dim1 () = class interface IDimension with member x.Size = 1 end end
type Dim2 () = class interface IDimension with member x.Size = 2 end end
The vector and the matrix can then be implemented like this
type Vector<'Dim when 'Dim :> IDimension
and 'Dim : (new : unit -> 'Dim)
> () =
class
let dim = new 'Dim()
let vs = Array.zeroCreate<float> dim.Size
member x.Dim = dim
member x.Values = vs
end
type Matrix<'RowDim, 'ColumnDim when 'RowDim :> IDimension
and 'RowDim : (new : unit -> 'RowDim)
and 'ColumnDim :> IDimension
and 'ColumnDim : (new : unit -> 'ColumnDim)
> () =
class
let rowDim = new 'RowDim()
let columnDim = new 'ColumnDim()
let vs = Array.zeroCreate<float> (rowDim.Size*columnDim.Size)
member x.RowDim = rowDim
member x.ColumnDim = columnDim
member x.Values = vs
end
Finally this allows us to write code like this:
let m76 = Matrix<Dim7, Dim6> ()
let v6 = Vector<Dim6> ()
let v7 = apply m76 v6 // Vector<Dim7>
// Doesn't compile because v7 has the wrong dimension
let vv = apply m76 v7
If you need a wide range of dimensions (because you have an algebra increments/decrements the dimensions of vectors/matrices) you could support that using some smart variant of church numerals.
If this is usable or not is entirely up the reader I think.
PS.
Perhaps unit of measures could have been used for this as well if they applied to more types than floats.
The general term for what you're looking for is dependent types, but F# does not support them.
I've seen an experiment in using type providers to mimic one particular flavor of dependent types (constraining the domain of a primitive type), but I wouldn't expect it to be possible to achieve what you want using type providers in their current form. They seem to be too whimsical for that.
Print format strings appear to be doing that (and in fact printers are a "Hello World" application for dependent types), but actually they work because they get special treatment by the compiler, and the mechanism for that is not extensible.
You're doomed to ensure correct lengths at runtime.
My best bet would be to use structs to encode actual vectors and ensure correctness on the API level that way, map them to arrays at the point where you're interacting with those matrix algebra libraries, then map the results back to structs with ample assertions when done.
The comment from #Justanothermetaprogrammer qualifies as an answer. Here is how it works in the real example. The matrix implementation in the example is based on MathNet.Numerics.LinearAlgebra:
open MathNet.Numerics.LinearAlgebra
type RealMatrix2x2 =
| RealMatrix2x2 of Matrix<double>
static member private createInternal (a : #seq<#seq<double>>) =
matrix a |> RealMatrix2x2
static member create
(
(a11, a12),
(a21, a22)
) =
RealMatrix2x2.createInternal
[|
[| a11; a12|]
[| a21; a22|]
|]
let m2 =
(
(1., 2.),
(3., 4.)
)
|> RealMatrix2x2.create
The tuple signatures and "re-mapping" into #seq<#seq<double>> can be easily code-generated using, for example, Excel or any other convenient tool for as many dimensions as necessary. In fact, the whole class along with any other necessary operator overrides (like multiplication of RealMatrix2x2 by RealMatrix2x2, ...) can be code generated for all necessary dimensions.
Hopefully this is coherent, albeit longwinded.
I am trying to create a property in one .fs file that I can set from a separate .fs file and then use that value in a module in the first .fs file... For instance,
In my first file function.fs, I would like to define a property theta.
I would then like to define a function Q in function.fs such that:
function Q = Q(r) and...
Q(r) is dependent on some calculations that are dependent on theta,
i.e
A1(theta), A2(theta), A3(theta)
Q returns a data set in the form of a list.
I would also like to maintain a set of theta values in my main .fs file program.fs (i.e.
theta = [90;120;150;180])
I would then like to generate a data sets from function.fs for each theta.
My thought was to do this by setting a value for a property theta, running the program to generate a data set, setting a new value for theta, running the program to generate a data set, repeat... I have done a fair amount of research, what is not clear to me is how I actually recall the value of the property in the code for Q(r).
I have successfully setup a property in my function.fs file that I can set from program.fs:
In function.fs I have:
namespace models.test
type ContactAngle() =
let mutable m_theta = 90.0
//read only property
member this.Empty =
m_theta = 90.0
//read-write property
//i think i'm onto something with this static...
member this.Angle
with get() =
m_theta
and set newAmt =
m_theta <- newAmt
//module HTModel =
And in program.fs I have:
open models.test
let me = new ContactAngle()
printfn "%A" me.Angle
me.Angle <- 120.0
printfn "%A" me.Angle
This allows me to redefine the value theta. Where I am struggling is how I now use the new property value in a function in function.fs.
I feel like I am missing something very elementary and need some help! Any insight would be greatly appreciated!
Since functions evaluate when they are called not when created (exactly like in, for example, C#) you can just create a normal function in your ContactAngle type like this:
member this.DoSomenthingWithTheta multiplier
m_theta <- m_theta * multiplier
You can reuse your mutable value anywhere in your class.
To clarify all that you should read 'members' section of F# language reference.
But if you want to use that value outside your type and in a place where you don't have your initiated instance. Well then You would have to take a different approach. For example create a static mutable field and expose it with static property. Or create a singleton to store your value throughout the application.
But this kind of kills the 'spirit' of functional programming :).
How do F# immutable types interface with C#. I'm just starting to learn F# and I'd like to mix it in with some C# code I have, but I want my F# classes to be immutable.
Let's say we're making a Vector class in F#. Vector.X and Vector.Y should be re-assignable, but only be returning a new Vector class. In C# this would take allot of legwork to make .WithX(float x) clone the existing object and return a new one. Is there an easy way to do this in F#?
I've been searching for some time and I can't seem to find any docs on this. So any help would be great.
And finally, if I imported this class into C# what would its interface look like? Will the F# code restrict me from doing something stupid like Vector.X = 10?
This will look similar regardless of whether it's C# or F#.
You say "in C# it will take legwork", but cmon, I think
Vector WithX(float x) { return new Vector(x, this.Y); }
is it, right?
In both C# and F#, to prevent assignment to the X property, you author a property with a 'getter' but no 'setter'.
I think you're making all of this out to be harder than it is, or maybe I'm misunderstanding what you're asking.
EDIT
For the (I think rare) case of where there are 20 field and you may want to change just a small arbitrary subset of them, I found a cute hack to use F# and C# optional parameters together nicely.
F# Code:
namespace global
open System.Runtime.InteropServices
type Util =
static member Some<'T>(x:'T) = Some x
type MyClass(x:int, y:int, z:string) =
new (toClone:MyClass,
[<Optional>] ?x,
[<Optional>] ?y,
[<Optional>] ?z) =
MyClass(defaultArg x toClone.X,
defaultArg y toClone.Y,
defaultArg z toClone.Z)
member this.X = x
member this.Y = y
member this.Z = z
F# client code:
let a = new MyClass(3,4,"five")
let b = new MyClass(a, y=44) // clone a but change y
C# client code:
var m = new MyClass(3, 4, "five");
var m2 = new MyClass(m, y:Util.Some(44)); // clone m but change y
That is, optional parameters are a nice way to do this, and while C# optional parameters have some limitations, you can expose F# optional parameters in a way that works ok with C#, as suggested above.
F# Record types have a built in way of doing exactly what you're asking:
type Vector = {X:float; Y:float}
let v1 = {X=1.; Y=2.}
let v2 = {v1 with X=3.}
How that interops with C#, I'm not sure (edit: see Brian's comment).
Vector will be immutable from any .NET language, since X and Y are implemented as getters without setters.