|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.ComponentModel; |
| 4 | +using System.Reactive.Linq; |
| 5 | + |
| 6 | +namespace Bonsai.Scripting.Python |
| 7 | +{ |
| 8 | + /// <summary> |
| 9 | + /// Represents an operator that uses a Python script to filter the elements |
| 10 | + /// of an observable sequence. |
| 11 | + /// </summary> |
| 12 | + [Obsolete] |
| 13 | + [DefaultProperty(nameof(Script))] |
| 14 | + [WorkflowElementCategory(ElementCategory.Condition)] |
| 15 | + [Description("A Python script used to determine which elements of the input sequence are accepted.")] |
| 16 | + public class PythonCondition : Combinator |
| 17 | + { |
| 18 | + /// <summary> |
| 19 | + /// Initializes a new instance of the <see cref="PythonCondition"/> class. |
| 20 | + /// </summary> |
| 21 | + public PythonCondition() |
| 22 | + { |
| 23 | + Script = "def process(value):\n return True"; |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Gets or sets the script that determines the criteria for the condition. |
| 28 | + /// </summary> |
| 29 | + [Editor("Bonsai.Scripting.Python.Design.PythonScriptEditor, Bonsai.Scripting.Python.Design", DesignTypes.UITypeEditor)] |
| 30 | + [Description("The script that determines the criteria for the condition.")] |
| 31 | + public string Script { get; set; } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Uses a Python script to filter the elements of an observable sequence. |
| 35 | + /// </summary> |
| 36 | + /// <typeparam name="TSource"> |
| 37 | + /// The type of the elements in the <paramref name="source"/> sequence. |
| 38 | + /// </typeparam> |
| 39 | + /// <param name="source"> |
| 40 | + /// The observable sequence to filter. |
| 41 | + /// </param> |
| 42 | + /// <returns> |
| 43 | + /// An observable sequence that contains the elements of the <paramref name="source"/> |
| 44 | + /// sequence that satisfy the condition. |
| 45 | + /// </returns> |
| 46 | + public override IObservable<TSource> Process<TSource>(IObservable<TSource> source) |
| 47 | + { |
| 48 | + return Observable.Defer(() => |
| 49 | + { |
| 50 | + var engine = PythonEngine.Create(); |
| 51 | + var scope = engine.CreateScope(); |
| 52 | + engine.Execute(Script, scope); |
| 53 | + |
| 54 | + PythonProcessor<TSource, bool> processor; |
| 55 | + if (PythonHelper.TryGetClass(scope, "Condition", out object condition)) |
| 56 | + { |
| 57 | + processor = new PythonProcessor<TSource, bool>(engine.Operations, condition); |
| 58 | + } |
| 59 | + else processor = new PythonProcessor<TSource, bool>(scope); |
| 60 | + |
| 61 | + if (processor.Load != null) |
| 62 | + { |
| 63 | + processor.Load(); |
| 64 | + } |
| 65 | + |
| 66 | + var result = source.Where(processor.Process); |
| 67 | + if (processor.Unload != null) |
| 68 | + { |
| 69 | + result = result.Finally(processor.Unload); |
| 70 | + } |
| 71 | + |
| 72 | + return result; |
| 73 | + }); |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments