chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
 
namespace OpenTap.Plugins.BasicSteps
{
    [Browsable(false)]
    [Display("Sweep Parameter Range", "Ranged based sweep step that iterates value of its parameters based on a selected range.", "Flow Control")]
    [AllowAnyChild]
    public class SweepParameterRangeStep : SweepParameterStepBase
    {
        [Display("Start", Group:"Sweep", Order: -2, Description: "The parameter value where the sweep will start.")]
        public decimal SweepStart { get; set; }
 
        [Display("Stop",  Group:"Sweep",Order: -1, Description: "The parameter value where the sweep will stop.")]
        public decimal SweepStop { get; set; }
 
        [Browsable(false)]
        public decimal SweepEnd { get { return SweepStop; } set { SweepStop = value; } }
        
        [Display("Step Size",  Group:"Sweep", Order: 1, Description: "The value to be increased or decreased between every iteration of the sweep.")]
        [EnabledIf(nameof(SweepBehavior), SweepBehavior.Linear, HideIfDisabled = true)]
        public decimal SweepStep {
            get
            {
                if (SweepPoints == 0) return 0;
                if (SweepPoints == 1) return 0;
                return (SweepStop - SweepStart) / (SweepPoints - 1);
            }
            set
            {
                if (decimal.Zero == value) return;
                var newv = (uint)Math.Round((SweepStop - SweepStart) / value) + 1;
                SweepPoints = newv;
            }
        }
 
        [Display("Points",  Group:"Sweep",Order: 1, Description: "The number of points to sweep.")]
        public uint SweepPoints { get; set; }
 
        private int iteration = 0;
        [Output(OutputAvailability.BeforeRun)]
        [Display("Iteration", "Shows the iteration of the sweep that is currently running or about to run.", "Sweep", Order: 1.5)]
        public string IterationInfo => $"{iteration} of {SweepPoints}";
 
        [Display("Behavior",  Group:"Sweep",Order: -3, Description: "Linear or exponential growth.")]
        public SweepBehavior SweepBehavior { get; set; }
 
        public override void PrePlanRun()
        {
            base.PrePlanRun();
            validateSweepMutex.WaitOne();
        }
 
        public override void PostPlanRun()
        {
            validateSweepMutex.ReleaseMutex();
            base.PostPlanRun();
        }
 
        public override IEnumerable<ParameterMemberData> AvailableParameters => base.AvailableParameters.Where(x => x.TypeDescriptor.IsNumeric());
        
 
        // Check if the test plan is running before validating sweeps.
        // the validateSweep might have been started before the plan started.
        // hence we use the validateSweepMutex to ensure that validation is done before 
        // the plan starts.
        bool isRunning => GetParent<TestPlan>()?.IsRunning ?? false;
        Mutex validateSweepMutex = new Mutex();
        string validateSweep(decimal Value)
        {   // Mostly copied from Run
            var props = AvailableParameters.ToArray();
            
            if (props.Length == 0) return "";
            if (isRunning) return ""; // Avoid changing the value during run when the gui asks for validation errors.
            if (!validateSweepMutex.WaitOne(0)) return "";
            var originalValues = props.Select(set => set.GetValue(this)).ToArray();
            try
            {
                var str = StringConvertProvider.GetString(Value, CultureInfo.InvariantCulture);
 
                foreach (var set in props)
                {
                    var val = StringConvertProvider.FromString(str, set.TypeDescriptor, this, CultureInfo.InvariantCulture);
                    set.SetValue(this, val);
                }
 
                return "";
            }
            catch (TargetInvocationException e)
            {
                return e.InnerException.Message;
            }
            finally
            {
                for (int i = 0; i < props.Length; i++)
                    props[i].SetValue(this, originalValues[i]);
                validateSweepMutex.ReleaseMutex();
            }
        }
        
        public SweepParameterRangeStep()
        {
            Name = "Sweep Range {Parameters}";
 
            SweepStart = 1;
            SweepStop = 100;
            SweepPoints = 100;
 
            Rules.Add(() => string.IsNullOrWhiteSpace(validateSweep(SweepStart)), () => validateSweep(SweepStart), "SweepStart");
            Rules.Add(() => string.IsNullOrWhiteSpace(validateSweep(SweepStop)), () => validateSweep(SweepStop), "SweepEnd");
 
            Rules.Add(() => ((SweepBehavior != SweepBehavior.Exponential)) || (SweepStart != 0), "Sweep start value must be non-zero.", "SweepStart");
            Rules.Add(() => ((SweepBehavior != SweepBehavior.Exponential)) || (SweepStop != 0), "Sweep end value must be non-zero.", "SweepEnd");
            Rules.Add(() => SweepPoints > 1, "Sweep points must be bigger than 1.", "SweepPoints");
            
            Rules.Add(() => ((SweepBehavior != SweepBehavior.Exponential)) || (Math.Sign(SweepStop) == Math.Sign(SweepStart)), "Sweep start and end value must have the same sign.", "SweepEnd", "SweepStart");
        }
 
        public static IEnumerable<decimal> LinearRange(decimal start,  decimal end, int points)
        {
            if (points == 0) yield break;
            for(int i = 0; i < points - 1; i++)
            {
                yield return (start * (points - 1- i) + end * (i)) / (points - 1);
            }
            yield return end;
        }
 
        public static IEnumerable<decimal> ExponentialRange(decimal start, decimal end, int points)
        {
            if (start == 0)
                throw new ArgumentException("Start value must be different than zero.");
            if (end == 0)
                throw new ArgumentException("End value must be different than zero.");
            if (Math.Sign(start) != Math.Sign(end))
                throw new ArgumentException("Start and end value must have the same sign.");
            
            var logs = Math.Log10((double) start);
            var loge = Math.Log10((double) end);
            return LinearRange((decimal)logs, (decimal)loge, points).Select(x => (decimal)Math.Pow(10, (double)x));
        }
        
        
        public override void Run()
        {
            base.Run();
 
            var selected = SelectedMembers.ToArray();
            var originalValues = selected.Select(set => set.GetValue(this)).ToArray();
 
 
            IEnumerable<decimal> range = LinearRange(SweepStart, SweepStop, (int)SweepPoints);
 
            if (SweepBehavior == SweepBehavior.Exponential)
                range = ExponentialRange(SweepStart, SweepStop, (int)SweepPoints);
 
            var disps = selected.Select(x => x.GetDisplayAttribute()).ToList();
            string names = string.Join(", ", disps.Select(x => x.Name));
            
            if (disps.Count > 1)
                names = string.Format("{{{0}}}", names);
 
            iteration = 0;
            foreach (var Value in range)
            {
                iteration++;
                var val = StringConvertProvider.GetString(Value, CultureInfo.InvariantCulture);
                foreach (var set in selected)
                {
                    try
                    {
                        var value = StringConvertProvider.FromString(val, set.TypeDescriptor, this, CultureInfo.InvariantCulture);
                        set.SetValue(this, value);
                    }
                    catch (TargetInvocationException ex)
                    {
                        Log.Error("Unable to set '{0}' to value '{2}': {1}", set.GetDisplayAttribute().Name, ex.InnerException.Message, Value);
                        Log.Debug(ex.InnerException);
                    }
                }
                // Notify that values might have changes
                OnPropertyChanged("");
 
                var AdditionalParams = new ResultParameters();
                AdditionalParams.Add("Sweep", "Iteration", iteration, null);
                foreach (var disp in disps)
                    AdditionalParams.Add(new ResultParameter(disp.Group.FirstOrDefault() ?? "", disp.Name, Value));
 
                Log.Info("Running child steps with {0} = {1} ", names, Value);
 
                var runs = RunChildSteps(AdditionalParams, BreakLoopRequested, throwOnBreak: false).ToArray();
                if (BreakLoopRequested.IsCancellationRequested) break;
                runs.ForEach(r => r.WaitForCompletion());
                if (runs.LastOrDefault()?.BreakConditionsSatisfied() == true)
                    break;
                
            }
            for (int i = 0; i < selected.Length; i++)
                selected[i].SetValue(this, originalValues[i]);
        }
    }
}