How to pass one Q# operation to another Q# operation from C# or F# - quantum-computing

I have the following Q# operations
operation VQC (cirq:((Double[],Qubit[])=>Unit is Adj),measurement:Pauli[], args: Double[], nQubits:Int) : Double {
let res=EstimateFrequencyA(cirq(args,_),Measure(measurement,_),nQubits,1000);
return 2.*res-1.;
}
operation Cirq(args:Double[],qs: Qubit[]):Unit is Adj{
Rz(args[0],qs[0] );
CNOT(qs[0],qs[1]);
Ry(args[1],qs[1]);
}
How can I pass the Cirq operation into the VQC operation from C# or F#?

Looks like you can use SimulatorBase.Get<> to get an instance of the operation type you need to pass and to pass it instead.
Here is C# driver code (F# should be similar):
using QuantumSimulator qsim = new QuantumSimulator();
Pauli[] paulis = { Pauli.PauliX, Pauli.PauliZ };
double[] doubles = { 2.0, 0.5 };
IAdjointable cirqInstance = qsim.Get<IAdjointable, Cirq>();
double result = VQC.Run(qsim, cirqInstance, new QArray<Pauli>(paulis), new QArray<Double>(doubles), 2).Result;
Console.WriteLine(result);

Related

How to use Clutter.ShaderEffect.set_uniform_value() properly?

I am trying set a uniform float of a Clutter.ShaderEffect. This works well if floating point Numbers are passed to set_uniform_value(). However, when you pass an integer Number, an OpenGL error (1282, Invalid operation) is thrown. It seems that the implementation assumes in this case that the uniform is actually of type int. Here is a minimal example:
const {Clutter, GObject} = imports.gi;
Clutter.init(null);
let stage = new Clutter.Stage({width: 200, height: 200});
let shader = new Clutter.ShaderEffect({shader_type: Clutter.ShaderType.FRAGMENT_SHADER});
shader.set_shader_source(`
uniform float value;
void main(void) {
cogl_color_out = vec4(value, 0, 0, 1);
}
`);
// This creates the OpenGL Error.
// shader.set_uniform_value('value', 1);
// This works however:
shader.set_uniform_value('value', 0.999);
stage.add_effect(shader);
stage.connect('destroy', () => Clutter.main_quit());
stage.show();
Clutter.main();
So how do I force set_uniform_value() to interpret the value as floating point number? Reading the documentation (https://gjs-docs.gnome.org/clutter6~6_api/clutter.shadereffect#method-set_uniform_value), I would assume that I could pass a GObject.Value - maybe like this:
let value = new GObject.Value();
value.init(GObject.TYPE_FLOAT);
value.set_float(1.0);
shader.set_uniform_value('value', value);
But this yields the error Invalid uniform of type 'GValue' for name 'value'. Maybe I now have a GObject.Value containing a GObject.Value containing a GObject.TYPE_FLOAT?
As of GJS 1.68.0 (GNOME 40), passing a GObject.Value works:
let value = new GObject.Value();
value.init(GObject.TYPE_FLOAT);
value.set_float(1);
shader.set_uniform_value('value', value);
if someone looks for this question, I have the answer:
https://gjs-docs.gnome.org/clutter7~7_api/clutter.shadereffect#method-set_uniform_value value - a GObject.Value GObject.TYPE_FLOAT for float
and in gjs GTK Javascript they have https://gjs-docs.gnome.org/clutter7~7_api/clutter.value_set_shader_float
value_set_shader_float(value,[float]) method - Value must have been initialized using %CLUTTER_TYPE_SHADER_FLOAT.
and in Javascript version of GTK they dont have any way to initialize that CLUTTER_TYPE_SHADER_FLOAT or GObject.TYPE_FLOAT
The solution is:
function make_float(val) {
return Math.floor(val)==val?val+0.000001:val;
}

Array parameters to and from postgresql stored procedures using Npgsql from F#

I have two SQL functions (procedures) in postgresql. They take and return array; their signatures are
create function arr_ret( x int) returns int[] as
and
create function arr_param( x int[] ) returns int as
The first function when executed returns
> ctx.Functions.ArrRet.Invoke(6);;
Executing SQL : EXEC arr_ret(6) - params
val it : Unit = ()
>
As can be seen, the signature of the invoke operation is Unit() = (); doesn't return anything. I would have expected Unit() = int list because the procedure is expected to return an array of integers.
The second function when executed
> ctx.Functions.ArrParam.Invoke( [1;2;3;4;5;6] );;
ctx.Functions.ArrParam.Invoke( [1;2;3;4;5;6] );;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
stdin(22,1): error FS0501: The member or object constructor 'Invoke' takes 0 argument(s) but is here given 1. The requir
ed signature is 'SqlDataProvider<...>.dataContext.Functions.ArrParam.Result.Invoke() : SqlDataProvider<...>.dataContext.
Functions.ArrParam.Result.SprocResult'.
Npgsql is not seeing the parameter (either input or output) that is of array type. The documentation says postgresql array and composite types are supported from 3.0+ version and I am using the latest 3.2.3
You are sending a single argument of type FSharpList into a method that expects params. The way you are using it will send the entire list as a single parameter.
ctx.Functions.ArrParam.Invoke(1, 2, 3, 4, 5, 6);;
The above will send them individually as you want, but not if you pass the entire collection. The reason for this is the type provider is trying to resolve the type of object instead treating the entire array as multiple arguments.
In C#, this would work fine, but not in F#.
Here's a good way to test.
In C# define this method:
public static void PrintArgs(params object[] args)
{
foreach (var arg in args)
{
Console.WriteLine($"Type: {arg.GetType().Name}");
}
}
In F# call it as:
PrintArgs(1, 2.0, true, "4")
PrintArgs([1; 2; 3; 4])
They result in:
>
Type: Int32
Type: Double
Type: Boolean
Type: String
val it : unit = ()
>
Type: FSharpList`1
val it : unit = ()
>
Your problem is what happens in the second call, it's actually a List that's being sent and not multiple arguments.

what is magic of Scala Array.apply

From array.scala of scala-2.10.4, The Array is defined as
final class Array[T](_length: Int) extends java.io.Serializable with java.lang.Cloneable {
/** The length of the array */
def length: Int = throw new Error()
def apply(i: Int): T = throw new Error()
def update(i: Int, x: T) { throw new Error() }
override def clone(): Array[T] = throw new Error()
}
Please note, the apply method will throw an exception! And for the accompany object Arrry, I find the following codes:
def apply[T: ClassTag](xs: T*): Array[T] = {
val array = new Array[T](xs.length)
var i = 0
for (x <- xs.iterator) { array(i) = x; i += 1 }
array
}
I know there is an implicit parameter which is ClassTag[T], what make me surprised is how
new Array[T] (xs.length)
is compiled. By decompiling the Array.class, I find that line is translated to :
public <T> Object apply(Seq<T> xs, ClassTag<T> evidence$2)
{
// evidence$2 is implicit parameter
Object array = evidence$2.newArray(xs.length());
...
}
I am really confused by this kind of translation, what is the rule under the hood?
Thanks
Chang
The Scala Array Class is just a fake wrapper for the runtime so you can use arrays in Scala. You're probably confused because those methods on the Array class throw exceptions. The reason they did this is so that if you actually end up using the fake class it blows up since really it should be using the java runtime array, which does not have a proper container class like Scala. You can see how the compiler handles it here. When your using arrays in Scala you're probably also using some implicits from predef like ArrayOps and WrappedArray for extra helper methods.
TLDR: Scala compiler magic makes arrays work with the java runtime under the hood.
On the JVM arrays are exempt from type-erasure, e.g. at runtime instead of Array[_] there is a difference between Array[Int], Array[String] and Array[AnyRef] for example. Unlike Java, Scala can handle this mostly transparently, so
class Foo {
val foo = new Array[Int](123)
}
has a direct byte-code invocation for creating the integer array, whereas
class Bar[A](implicit ev: reflect.ClassTag[A]) {
val bar = new Array[A](123)
}
is solved by using the implicit type evidence parameter of type ClassTag[A] so that at runtime the JVM can still create the correct array. This is translated into the call you saw, ev.newArray(123).

What is the canonical way to convert an Array<Byte> to a ByteArray

If have an Array and want to convert it to a ByteArray, how should I go about it? The following for instance fails:
var srcArray = Array<Byte>(10, { 0 })
var tgtArray: ByteArray = srcArray as ByteArray
I do realize though that specialized classes such as ByteArray are:
... not related to the Array class and are compiled down to Java’s primitive arrays for maximum performance.
So, the fact that my approach fails shouldn't surprise me - but what is the canonical way to make the conversion? Simply iterate through srcArray and populate tgtArray one index at a time - or is there a more elegant solution I'm missing?
I don't see any built-in functions apart from the obvious loop-based approach. But you could define an extension function like this yourself:
fun Array<Byte>.toPrimitive(): ByteArray {
val tgtArray: ByteArray = ByteArray(this.size())
for (i in this.indices) {
tgtArray[i] = this[i]
}
return tgtArray
}
fun test() {
val srcArray = Array<Byte>(10, { 0 })
val tgtArray: ByteArray = srcArray.toPrimitive()
}
Kotlin has this in the stdlib as an extension function Array<Byte>.toByteArray()
val srcArray = Array<Byte>(10, { 0 })
val tgtArray = srcArray.toByteArray()
(Note: I changed your var to val which is more common in Kotlin to use read-only values)
You will see similar ones for other primitive data types that have array implementations. You can see them all in the Kotlin documentation for Array extension functions.

Can generic list utilities use Vectors (AS3)?

Using Object or * as a type for a Vector doesn't provide generic functionality (like List in Java). Witness:
public static function someGenericVectorUtil (value:Vector.<*>) :void {
// do stuff to/with the Vector
}
var someVector:Vector.<Number>;
someGenericVectorUtil(someVector); // compile-time implicit coercion error
So, perhaps we redefine the utility method to accept an Array. But there's no easy way to convert Vectors going into the utility to Arrays, nor an easy way to pack them back in afterwards, resulting in code like this:
public static function someGenericArrayUtil (value:Array) :void {
// do stuff to/with the formerly-known-as-Vector
}
var someVector:Vector.<Number>;
var tempArray:Array = new Array(someVector.length);
for (var i:uint=0; i<someVector.length; i++) {
tempArray[i] = someVector[i];
}
someGenericVectorUtil(tempArray);
someVector = Vector.<Number>([tempArray]);
Needless to say, that's pretty hideous. Okay, so let's move the Vector-Array-Vector nonsense into a utility:
public static function vectorToArray (Vector.<*>) :Array {
// oh wait....that Vector.<*> param is useless,
// as demonstrated earlier.
}
Any way to straighten out this mess? Or should I just stop using Vectors when I think I might need to run them through generic utilities? (Obviously, also not really much of an option...)
public static function someGenericVectorUtil (value:Vector.<*>) :void {
// do stuff to/with the Vector
}
var someVector:Vector.<Number>;
someGenericVectorUtil(Vector.<*>(someVector));
^ it works. Also try with Array.
This is not an answer but more a long comment to #Lukasz's answer.
The problem with his answer is that you're actually creating a new Vector, so you need to return the Vector from someGenericVectorUtil and re-cast it. E.g. try:
var v:Vector.<int> = Vector.<int>([1,2,3]);
trace( v == Vector.<int>( Vector.<*>( v ) ) ); // traces false
That code just creates a simple Vector of ints, then compares it with a version of itself casted (first to *, then back to int). If you trace the Vectors out, they'll trace identical, but the actual Vectors references themselves aren't the same object. Thus if you have a utility function that modifies the Vector (e.g. a shuffle or randomise function), nothing will change.
E.g:
var v:Vector.<int> = Vector.<int>([1,2,3]);
trace( v ); // traces "1,2,3"
// shuffle() randomises the elements in a vector - this first call won't work
// as the cast creates a new vector
VectorUtil.shuffle( Vector.<*>( v ) );
trace( v ); // traces "1,2,3"
// we need to recast it back, and change shuffle() to return the vector
v = Vector.<int>( VectorUtil.shuffle( Vector.<*>( v ) ) );
trace( v ); // traces "3,1,2"
As you can see, it starts to get a bit ugly towards the end, and if you're keeping track of the Vector anywhere else, you'll need to update the references, but it's the only solution that I've found so far :S

Resources