Esempio n. 1
0
        public bool Equal(Cdn.Expression other, bool asstring)
        {
            bool raw_ret = cdn_expression_equal(Handle, other == null ? IntPtr.Zero : other.Handle, asstring);
            bool ret     = raw_ret;

            return(ret);
        }
Esempio n. 2
0
        public Cdn.Expression[][] AllIndices()
        {
            int num = cdn_operator_num_indices(Handle);

            if (num == 0)
            {
                return(new Cdn.Expression[0][]);
            }

            IntPtr rawret = cdn_operator_all_indices(Handle);

            Cdn.Expression[][] ret;

            IntPtr[] data = new IntPtr[num];
            Marshal.Copy(rawret, data, 0, (int)num);

            ret = new Cdn.Expression[num][];

            for (int i = 0; i < num; ++i)
            {
                ret[i] = (Cdn.Expression[])GLib.Marshaller.ListPtrToArray(data[i],
                                                                          typeof(GLib.SList),
                                                                          false,
                                                                          false,
                                                                          typeof(Cdn.Expression));
            }

            return(ret);
        }
Esempio n. 3
0
        public DelayedState(InstructionCustomOperator delayed, double delay, Cdn.Expression expr, Flags type) : base(delayed, expr, type)
        {
            d_delayed = delayed;
            d_delay   = delay;

            d_size = new Size((uint)System.Math.Round(d_delay / Options.Instance.DelayTimeStep));
        }
Esempio n. 4
0
        public EdgeAction(string target, Cdn.Expression equation) : base(IntPtr.Zero)
        {
            if (GetType() != typeof(EdgeAction))
            {
                ArrayList vals  = new ArrayList();
                ArrayList names = new ArrayList();
                names.Add("target");
                vals.Add(new GLib.Value(target));

                if (equation != null)
                {
                    names.Add("equation");
                    vals.Add(new GLib.Value(equation));
                }

                CreateNativeObject((string[])names.ToArray(typeof(string)), (GLib.Value[])vals.ToArray(typeof(GLib.Value)));
            }
            else
            {
                IntPtr native_target = GLib.Marshaller.StringToPtrGStrdup(target);
                Raw = cdn_edge_action_new(native_target, equation == null ? IntPtr.Zero : equation.Handle);
                GLib.Marshaller.Free(native_target);
            }

            if (Raw != IntPtr.Zero)
            {
                g_object_ref_sink(Raw);
            }
        }
Esempio n. 5
0
        public Cdn.Expression ToExpression()
        {
            IntPtr raw_ret = cdn_expression_tree_iter_to_expression(Handle);

            Cdn.Expression ret = GLib.Object.GetObject(raw_ret) as Cdn.Expression;
            return(ret);
        }
Esempio n. 6
0
        public Variable(string name, Cdn.Expression expression, Cdn.VariableFlags flags) : base(IntPtr.Zero)
        {
            if (GetType() != typeof(Variable))
            {
                ArrayList vals  = new ArrayList();
                ArrayList names = new ArrayList();
                names.Add("name");
                vals.Add(new GLib.Value(name));
                if (expression != null)
                {
                    names.Add("expression");
                    vals.Add(new GLib.Value(expression));
                }
                names.Add("flags");
                vals.Add(new GLib.Value(flags));
                CreateNativeObject((string[])names.ToArray(typeof(string)), (GLib.Value[])vals.ToArray(typeof(GLib.Value)));
                return;
            }
            IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup(name);

            Raw = cdn_variable_new(native_name, expression == null ? IntPtr.Zero : expression.Handle, (int)flags);
            GLib.Marshaller.Free(native_name);

            if (Raw != IntPtr.Zero)
            {
                g_object_ref_sink(Raw);
            }
        }
Esempio n. 7
0
        public bool DependsOn(Cdn.Expression depends_on)
        {
            bool raw_ret = cdn_expression_depends_on(Handle, depends_on == null ? IntPtr.Zero : depends_on.Handle);
            bool ret     = raw_ret;

            return(ret);
        }
Esempio n. 8
0
        public Cdn.EdgeAction GetActionWithIndexAndPhases(string target, Cdn.Expression index, GLib.SList phases)
        {
            IntPtr native_target = GLib.Marshaller.StringToPtrGStrdup(target);
            IntPtr raw_ret       = cdn_edge_get_action_with_index_and_phases(Handle, native_target, index == null ? IntPtr.Zero : index.Handle, phases == null ? IntPtr.Zero : phases.Handle);

            Cdn.EdgeAction ret = GLib.Object.GetObject(raw_ret) as Cdn.EdgeAction;
            GLib.Marshaller.Free(native_target);
            return(ret);
        }
Esempio n. 9
0
        public static Cdn.Expression Sum(Cdn.Expression[] expressions)
        {
            GLib.SList list = new GLib.SList(expressions, typeof(Cdn.Expression), true, false);

            IntPtr raw_ret = cdn_expression_sum(list == null ? IntPtr.Zero : list.Handle);

            Cdn.Expression ret = GLib.Object.GetObject(raw_ret) as Cdn.Expression;
            return(ret);
        }
Esempio n. 10
0
        private void Expand()
        {
            if (d_expression != null)
            {
                return;
            }

            if (d_expressionUnexpanded != null)
            {
                d_expression = Knowledge.Instance.ExpandExpression(d_expressionUnexpanded);
                return;
            }

            List <Cdn.Expression> exprs = new List <Cdn.Expression>();
            Variable v = d_object as Variable;

            if (d_actions.Length != 0)
            {
                foreach (EdgeAction action in d_actions)
                {
                    Cdn.Variable subvar;

                    if (Knowledge.Instance.EventActionProperties.TryGetValue(action, out subvar))
                    {
                        Cdn.Expression e = new Cdn.Expression(subvar.Name);
                        e.Instructions = new Cdn.Instruction[] { new Cdn.InstructionVariable(subvar) };

                        exprs.Add(e);
                    }
                    else
                    {
                        exprs.Add(action.Equation);
                    }
                }
            }
            else
            {
                if (v != null)
                {
                    exprs.Add(v.Expression);
                }
                else
                {
                    Expression e = d_object as Expression;

                    if (e != null)
                    {
                        exprs.Add(e);
                    }
                }
            }

            Dictionary <Instruction, Instruction> instmap = new Dictionary <Instruction, Instruction>();

            d_expression = Knowledge.Instance.ExpandExpression(instmap, exprs.ToArray());
            Knowledge.Instance.UpdateInstructionMap(instmap);
        }
Esempio n. 11
0
        private void Resolve(Node node, Cdn.Expression expression, HashSet <Cdn.Expression> seen, Dictionary <object, State> mapping)
        {
            if (seen.Contains(expression))
            {
                return;
            }

            Resolve(node, expression.Instructions, seen, mapping);
        }
Esempio n. 12
0
        private Cdn.Expression Inline(Dictionary <Instruction, Instruction> instmap, Cdn.Expression expr)
        {
            List <Cdn.Instruction> instructions = new List <Instruction>();

            foreach (Instruction inst in expr.Instructions)
            {
                InstructionVariable variable = inst as InstructionVariable;

                if (variable != null)
                {
                    // See if we need to expand it
                    Variable v = variable.Variable;

                    if (State(v) == null)
                    {
                        if (variable.HasSlice)
                        {
                            // Need to promote it here. Inlining a slice is
                            // complicated
                            var s = ExpandedState(v);

                            AddState(null, s);
                            AddAux(s, null);
                        }
                        else
                        {
                            var sub = Inline(instmap, v.Expression);

                            // Expand the instruction
                            foreach (var i in sub.Instructions)
                            {
                                instructions.Add(i);
                            }

                            continue;
                        }
                    }
                }

                var cp = inst.Copy() as Instruction;

                if (instmap != null)
                {
                    instmap.Add(inst, cp);
                }

                instructions.Add(cp);
            }

            var e = new Cdn.Expression("");

            e.SetInstructionsTake(instructions.ToArray());

            return(e);
        }
Esempio n. 13
0
        public Function(string name, Cdn.Expression expression) : base(IntPtr.Zero)
        {
            if (GetType() != typeof(Function))
            {
                throw new InvalidOperationException("Can't override this constructor.");
            }
            IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup(name);

            Raw = cdn_function_new(native_name, expression == null ? IntPtr.Zero : expression.Handle);
            GLib.Marshaller.Free(native_name);
        }
Esempio n. 14
0
        public Cdn.Expression Copy()
        {
            IntPtr raw_ret = cdn_expression_copy(Handle);

            if (raw_ret != IntPtr.Zero)
            {
                g_object_ref_sink(Raw);
            }

            Cdn.Expression ret = GLib.Object.GetObject(raw_ret, true) as Cdn.Expression;
            return(ret);
        }
Esempio n. 15
0
        public Cdn.EdgeAction AddAction(string target, Cdn.Expression expression)
        {
            Cdn.EdgeAction action = new Cdn.EdgeAction(target, expression);

            if (AddAction(action))
            {
                return(action);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 16
0
 protected virtual void OnExpressionChanged(Cdn.Expression expression)
 {
     GLib.Value      ret             = GLib.Value.Empty;
     GLib.ValueArray inst_and_params = new GLib.ValueArray(2);
     GLib.Value[]    vals            = new GLib.Value [2];
     vals [0] = new GLib.Value(this);
     inst_and_params.Append(vals [0]);
     vals [1] = new GLib.Value(expression);
     inst_and_params.Append(vals [1]);
     g_signal_chain_from_overridden(inst_and_params.ArrayPtr, ref ret);
     foreach (GLib.Value v in vals)
     {
         v.Dispose();
     }
 }
Esempio n. 17
0
        public FunctionArgument(string name, Cdn.Expression defaultValue, bool isexplicit) : base(IntPtr.Zero)
        {
            if (GetType() != typeof(FunctionArgument))
            {
                throw new InvalidOperationException("Can't override this constructor.");
            }

            IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup(name);

            Raw = cdn_function_argument_new(native_name, defaultValue != null ? defaultValue.Handle : IntPtr.Zero, isexplicit);
            GLib.Marshaller.Free(native_name);

            if (Raw != IntPtr.Zero)
            {
                g_object_ref_sink(Raw);
            }
        }
Esempio n. 18
0
        public Cdn.Expression ExpandExpression(Dictionary <Instruction, Instruction> instmap, params Cdn.Expression[] expressions)
        {
            if (expressions.Length == 0)
            {
                var ret = new Cdn.Expression("0");
                ret.Compile(null, null);
                return(ret);
            }

            List <Cdn.Expression> inlined = new List <Expression>();

            for (int i = 0; i < expressions.Length; ++i)
            {
                inlined.Add(Inline(instmap, expressions[i]));
            }

            return(Cdn.Expression.Sum(inlined.ToArray()));
        }
Esempio n. 19
0
        private IEnumerable <VariableDependency> VariableExpressionDependencies(Cdn.Expression expr)
        {
            if (expr == null)
            {
                return(new VariableDependency[] {});
            }

            if (s_variableDependencies == null)
            {
                s_variableDependencies = new Dictionary <Cdn.Expression, List <VariableDependency> >();
            }

            List <VariableDependency> lst;

            if (s_variableDependencies.TryGetValue(expr, out lst))
            {
                return(lst);
            }

            lst = new List <VariableDependency>();
            s_variableDependencies[expr] = lst;

            foreach (var instr in expr.Instructions)
            {
                InstructionVariable v = instr as InstructionVariable;

                if (v != null)
                {
                    lst.Add(new VariableDependency {
                        Variable = v.Variable, Instruction = v
                    });
                }
            }

            foreach (var ex in expr.Dependencies)
            {
                lst.AddRange(VariableExpressionDependencies(ex));
            }

            return(lst);
        }
Esempio n. 20
0
        public Event(string id, Cdn.Expression condition, double approximation) : base(IntPtr.Zero)
        {
            if (GetType() != typeof(Event))
            {
                ArrayList vals  = new ArrayList();
                ArrayList names = new ArrayList();
                names.Add("id");
                vals.Add(new GLib.Value(id));
                if (condition != null)
                {
                    names.Add("condition");
                    vals.Add(new GLib.Value(condition));
                }
                names.Add("approximation");
                vals.Add(new GLib.Value(approximation));
                CreateNativeObject((string[])names.ToArray(typeof(string)), (GLib.Value[])vals.ToArray(typeof(GLib.Value)));
                return;
            }
            IntPtr native_id = GLib.Marshaller.StringToPtrGStrdup(id);

            Raw = cdn_event_new(native_id, condition == null ? IntPtr.Zero : condition.Handle, approximation);
            GLib.Marshaller.Free(native_id);
        }
Esempio n. 21
0
        public State(object obj, Cdn.Expression expr, Flags type, params EdgeAction[] actions)
        {
            d_object  = obj;
            d_actions = actions;

            if (d_actions == null)
            {
                d_actions = new EdgeAction[0];
            }

            Variable variable = obj as Variable;

            if (variable != null && variable.HasFlag(VariableFlags.Integrated))
            {
                d_type = Flags.Integrated;
            }

            if (expr != null)
            {
                d_expressionUnexpanded = expr;
            }

            d_type |= type;
        }
Esempio n. 22
0
 public void AddSetVariable(Cdn.Variable variable, Cdn.Expression value)
 {
     cdn_event_add_set_variable(Handle, variable == null ? IntPtr.Zero : variable.Handle, value == null ? IntPtr.Zero : value.Handle);
 }
Esempio n. 23
0
        public void Generate()
        {
            Profile.Do("load network", () => {
                LoadNetwork();
            });

            if (Options.Instance.Validate)
            {
                d_validator = new Validator(d_network);
            }

            if (Options.Instance.DelayTimeStep > 0)
            {
                Cdn.Expression    expr  = new Cdn.Expression(Options.Instance.DelayTimeStep.ToString("R"));
                Cdn.Instruction[] instr = new Cdn.Instruction[1];
                instr[0]          = new Cdn.InstructionNumber(Options.Instance.DelayTimeStep);
                expr.Instructions = instr;

                d_network.Integrator.AddVariable(new Cdn.Variable("delay_dt", expr, Cdn.VariableFlags.Out));
            }

            Profile.Do("initialize knowledge", () => {
                // Initialize the knowledge
                Knowledge.Initialize(d_network);
            });

            if (!Options.Instance.NoSparsity)
            {
                Profile.Do("sparsity", () => {
                    var sparsity = new Sparsity();
                    sparsity.Optimize();
                });
            }

            var t = Profile.Begin("collect");

            // Collect all the equations
            Tree.Collectors.Result collection = Collect();

            t.End();

            t = Profile.Begin("filter");

            // Filter conflicts and resolve final embeddings
            Tree.Embedding[] embeddings = Filter(collection);

            t.End();

            t = Profile.Begin("resolve equations");

            // Resolve final equations
            Dictionary <State, Tree.Node> equations = ResolveEquations(embeddings);

            t.End();

            // Create program
            t = Profile.Begin("create program");

            Programmer.Program program = new Programmer.Program(ProgrammerOptions(), embeddings, equations);

            t.End();

            bool outistemp = false;

            // Write program
            if (Options.Instance.Validate || Options.Instance.Compile)
            {
                // Create a new temporary directory for the output files
                string path = Path.GetTempFileName();
                File.Delete(path);

                Directory.CreateDirectory(path);
                program.Options.Output = path;

                outistemp = true;
            }
            else
            {
                Directory.CreateDirectory(program.Options.Output);
            }

            t = Profile.Begin("write program");

            d_writtenFiles = Options.Instance.Formatter.Write(program);

            t.End();

            if (Options.Instance.PrintCompileSource)
            {
                foreach (string filename in d_writtenFiles)
                {
                    Console.WriteLine("File: {0}", filename);
                    Console.WriteLine(File.ReadAllText(filename));
                }
            }

            if (Options.Instance.Validate && !Options.Instance.PrintCompileSource)
            {
                try
                {
                    d_validator.Validate(program, d_writtenFiles);
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.Message);

                    Directory.Delete(program.Options.Output, true);
                    Environment.Exit(1);
                }
            }
            else if (Options.Instance.Compile)
            {
                var files = Options.Instance.Formatter.Compile(Options.Instance.Verbose);

                if (Options.Instance.Verbose)
                {
                    Log.WriteLine("Compiled {0}...", String.Join(", ", Array.ConvertAll <string, string>(files, a => Path.GetFileName(a))));
                }

                if (!String.IsNullOrEmpty(Options.Instance.Output))
                {
                    try
                    {
                        Directory.CreateDirectory(Options.Instance.Output);
                    }
                    catch
                    {
                    }
                }

                foreach (var f in files)
                {
                    var dest = Path.GetFileName(f);

                    if (!String.IsNullOrEmpty(Options.Instance.Output))
                    {
                        dest = Path.Combine(Options.Instance.Output, dest);
                    }

                    try
                    {
                        File.Delete(dest);
                    } catch {}

                    File.Move(f, dest);
                }
            }

            if (outistemp)
            {
                try
                {
                    Directory.Delete(program.Options.Output, true);
                } catch {};
            }
        }
Esempio n. 24
0
 public ExpressionTreeIter(Cdn.Expression expression)
 {
     Raw = cdn_expression_tree_iter_new(expression == null ? IntPtr.Zero : expression.Handle);
 }
Esempio n. 25
0
        private void PromoteEdgeSlices()
        {
            // This function splits all the edge actions on variables based
            // on the slice on which the operate on the target variable.
            var cp = d_actionedVariables;

            d_actionedVariables = new Dictionary <Variable, EdgeAction[]>();

            foreach (var pair in cp)
            {
                var variable = pair.Key;
                var actions  = pair.Value;

                var split = SplitActionsPerSlice(actions);

                if (split.Count == 1)
                {
                    // That's ok, no diversity means we can just use the
                    // normal code path
                    d_actionedVariables[pair.Key] = pair.Value;
                    continue;
                }

                // Contains a set of instructions for each value in the matrix
                // representing the final, new equation. Each value in the matrix
                // is a set of instructions because it can be a sum
                List <Cdn.Instruction>[] instructions = new List <Instruction> [variable.Dimension.Size()];

                // Ai! Cool stuff needs to happen here. Split out new
                // variables for these equations and setup a new edge action
                // representing the fully combined set. Complex you say? Indeed!
                foreach (var elem in split)
                {
                    // Combine elements with the same indices by simply doing a sum
                    var            eqs = Array.ConvertAll <Cdn.EdgeAction, Cdn.Expression>(elem.ToArray(), a => a.Equation);
                    Cdn.Expression sum = Cdn.Expression.Sum(eqs);

                    // Now make a variable for it
                    var nv = new Cdn.Variable(UniqueVariableName(variable.Object, String.Format("__d{0}", variable.Name)), sum, VariableFlags.None);
                    variable.Object.AddVariable(nv);

                    // Add relevant instructions as per slice
                    var slice = elem[0].Indices;

                    if (slice == null || slice.Length == 0)
                    {
                        // Empty slice is just the full range
                        slice = new int[variable.Dimension.Size()];

                        for (int i = 0; i < slice.Length; ++i)
                        {
                            slice[i] = i;
                        }
                    }

                    for (int i = 0; i < slice.Length; ++i)
                    {
                        if (instructions[slice[i]] == null)
                        {
                            instructions[slice[i]] = new List <Instruction>();
                        }

                        var vinstr = new Cdn.InstructionVariable(nv);

                        vinstr.SetSlice(new int[] { i }, new Cdn.Dimension {
                            Rows = 1, Columns = 1
                        });
                        instructions[slice[i]].Add(vinstr);
                    }
                }

                List <Cdn.Instruction> ret = new List <Instruction>();

                // Create substitute edge action
                foreach (var i in instructions)
                {
                    if (i == null)
                    {
                        ret.Add(new Cdn.InstructionNumber("0"));
                    }
                    else
                    {
                        // Add indexing instructions
                        ret.AddRange(i);

                        // Then add simple plus operators
                        for (int j = 0; j < i.Count - 1; ++j)
                        {
                            ret.Add(new Cdn.InstructionFunction((uint)Cdn.MathFunctionType.Plus, null, 2));
                        }
                    }
                }

                var minstr = new Cdn.InstructionMatrix(new Cdn.StackArgs(instructions.Length), variable.Dimension);
                ret.Add(minstr);

                var retex = new Cdn.Expression("");
                retex.SetInstructionsTake(ret.ToArray());

                var action = new Cdn.EdgeAction(variable.Name, retex);
                ((Cdn.Node)variable.Object).SelfEdge.AddAction(action);

                d_actionedVariables[variable] = new EdgeAction[] { action };
            }
        }
Esempio n. 26
0
		public void Set(IntPtr gerror, Cdn.Object objekt, Cdn.Variable property, Cdn.EdgeAction action, Cdn.Expression expression) {
			cdn_compile_error_set(Handle, gerror, objekt == null ? IntPtr.Zero : objekt.Handle, property == null ? IntPtr.Zero : property.Handle, action == null ? IntPtr.Zero : action.Handle, expression == null ? IntPtr.Zero : expression.Handle);
		}
Esempio n. 27
0
 public static Node Create(State state, Cdn.Expression expression)
 {
     return(Create(state, expression.Instructions));
 }
 void InvokeNative(Cdn.Expression expression)
 {
     native_cb(expression == null ? IntPtr.Zero : expression.Handle, __data);
 }
Esempio n. 29
0
 public ModifyExpression(Cdn.Expression expr, string expression)
 {
     d_expr           = expr;
     d_expression     = expression;
     d_prevExpression = expr.AsString;
 }