-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKinematicsLab.m
More file actions
1676 lines (1358 loc) · 61.8 KB
/
KinematicsLab.m
File metadata and controls
1676 lines (1358 loc) · 61.8 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef KinematicsLab < matlab.apps.AppBase
% Streamline / Pathline / Streakline explorer for 2D velocity fields
%
% Educational tool to illustrate core concepts in kinematics and fluid
% mechanics for steady and unsteady flows. The app provides an interactive
% environment to compare:
%
% (i) the instantaneous velocity field (quiver),
% (ii) streamlines at the current time,
% (iii) a pathline of a single Lagrangian tracer particle, and
% (iv) a streakline formed by continuously releasing particles from a
% fixed location.
%
% The goal is to highlight the differences between streamlines, pathlines,
% and streaklines, and how/when they coincide (e.g., in steady flows).
%
% Author: Alberto Cuadra Lara
%
% Last update: 19/02/2026
properties (Access = public)
UIFigure matlab.ui.Figure
LeftPanel matlab.ui.container.Panel
Axes matlab.ui.control.UIAxes
ProblemDropDown matlab.ui.control.DropDown
% Visibility
VelCheckBox matlab.ui.control.CheckBox
StreamCheckBox matlab.ui.control.CheckBox
PathCheckBox matlab.ui.control.CheckBox
StreakCheckBox matlab.ui.control.CheckBox
% Color pickers
VelColorPicker matlab.ui.control.ColorPicker
StreamColorPicker matlab.ui.control.ColorPicker
PathColorPicker matlab.ui.control.ColorPicker
StreakColorPicker matlab.ui.control.ColorPicker
% Parameters
V0Field matlab.ui.control.NumericEditField
V0Label matlab.ui.control.Label
X0Field matlab.ui.control.NumericEditField
Y0Field matlab.ui.control.NumericEditField
OmegaField matlab.ui.control.NumericEditField
OmegaLabel matlab.ui.control.Label
X0Label matlab.ui.control.Label
Y0Label matlab.ui.control.Label
% Buttons
RunButton matlab.ui.control.Button
StopButton matlab.ui.control.Button
ClearButton matlab.ui.control.Button
end
properties (Access = private)
% Simulation settings
FPS double = 60 % Fixed simulation frame rate [Hz]
TMAX double = 12 % Reference max time (used only for axis sizing in uniform flows)
DTSTREAK double = 0.2 % Time interval between streak particle releases [s]
DTPATHLINE double = 1/60 % Time step used for pathline precomputation [s]
numPointsPathline double = 1000 % Maximum number of points stored for a pathline polyline
maxStreakPts double = 1200 % Maximum number of streak particles retained
tickCount uint64 = uint64(0) % Total number of simulation ticks since start
numStreamlines int32 = 6 % Number of streamlines to display
numPointsStreamline double = 200 % Grid resolution for streamline generation via ψ contours
numContoursStreamline int32 = 6 % Number of streamline contours to display (when using ψ contour method)
% Timer / simulation state
Tmr = timer.empty % Timer object driving the simulation loop
t double = 0 % Current simulation time [s]
isRunning logical = false % True when the simulation is running
% Re-entrancy guards
isResetting logical = false % Prevents timer callback execution during reset
isTicking logical = false % Prevents reset execution during timer callback
% Graphics handles
qh % Quiver plot handle (velocity field)
srcDot % Source point marker handle
streamH = gobjects(0) % Streamline line object handles
pathLine % Pathline polyline handle
pDot % Pathline particle marker handle
streakLine % Streakline polyline handle
streakDots % Streak particle marker handles
% Grid for quiver visualization
xg double % Quiver grid x-coordinates
yg double % Quiver grid y-coordinates
% Axis limits
xMin double % Minimum x-axis limit
xMax double % Maximum x-axis limit
yMin double % Minimum y-axis limit
yMax double % Maximum y-axis limit
% Histories
pathX double = 0 % Pathline history: x positions
pathY double = 0 % Pathline history: y positions
pathT double = 0 % Pathline history: time samples
pathBox double = [0 0 0 0] % Pathline bounding box (used for validity / clipping checks)
streakX double = 0 % Streakline history: x positions
streakY double = 0 % Streakline history: y positions
lastReleaseT double = 0 % Time of last streak particle release
% UI styling
fontsizeLabels = 18 % Font size for axis labels and UI controls
% View / camera behaviour
qNx double = 14 % Number of quiver grid points in x
qNy double = 10 % Number of quiver grid points in y
viewDirty logical = false % Indicates pending view update (axis/grid change)
lastViewApplyT double = 0 % Time when the view was last applied
viewApplyMinPeriod double = 1/20 % Minimum interval between view updates [s] (max 20 Hz)
% Axis listeners
xLimListener event.listener = event.listener.empty % Listener for x-axis limit changes
yLimListener event.listener = event.listener.empty % Listener for y-axis limit changes
% Flow
Flows struct = struct( ...
'Label', {}, ... % Dropdown label
'Velocity', {}, ... % @(app,x,y,t) -> [u,v]
'AxisLimits', {}, ... % @(app) -> [xMin xMax yMin yMax]
'Streamlines', {}, ... % @(app,tFix,n) -> cell arrays {x_i},{y_i} (optional)
'UsesV0', {}, ...
'UsesOmega', {}, ...
'IsUnsteady', {} );
flowIndex uint16 = 1; % active flow index into Flows
end
methods (Access = public)
function app = KinematicsLab
% Constructor
createComponents(app);
startup(app);
end
function delete(app)
% Destructor
stopTimer(app);
if isvalid(app.UIFigure)
delete(app.UIFigure);
end
end
function addFlow(app, flow)
% Add a new flow definition to the Flow library
%
% Args:
% flow (struct): Struct defining the flow, with at least the required fields
%
% Note:
% * The required fields are Label and Velocity, which define the dropdown label and the velocity function, respectively.
% * The velocity function should have the signature @(app,x,y,t) -> [u,v], where (x,y) are coordinates and t is time.
% * Optional fields include AxisLimits (for automatic axis sizing), Streamlines (for custom streamline generation), and flags indicating whether the flow uses V0, omega, or is unsteady.
%
% Example:
% app.addFlow(struct(
% 'Label', 'Steady uniform: u=V0, v=0', ...
% 'UsesV0', true, 'UsesOmega', false, 'IsUnsteady', false, ...
% 'Velocity', @(app,x,y,t) deal(app.V0Field.Value + 0*x, 0 + 0*y), ...
% 'AxisLimits', @(app) axisLimitsSteadyUniform(app), ...
% 'Streamlines', @(app,tFix,n) streamlinesUniform(app,tFix,n) ...
% ));
arguments
app
flow struct
end
mustHave = {'Label','Velocity'};
for k = 1:numel(mustHave)
if ~isfield(flow, mustHave{k})
error('addFlow:MissingField', 'Flow must define "%s".', mustHave{k});
end
end
% Defaults
if ~isfield(flow,'UsesV0'), flow.UsesV0 = false; end
if ~isfield(flow,'UsesOmega'), flow.UsesOmega = false; end
if ~isfield(flow,'IsUnsteady'), flow.IsUnsteady = false; end
if ~isfield(flow,'Streamlines'), flow.Streamlines = []; end
if ~isfield(flow,'AxisLimits')
flow.AxisLimits = @(app) defaultAxisLimits(app); % fallback
end
app.Flows(end+1) = flow;
% Keep dropdown synced
if ~isempty(app.ProblemDropDown) && isvalid(app.ProblemDropDown)
app.ProblemDropDown.Items = {app.Flows.Label};
end
end
end
methods (Access = private)
function startup(app)
% Initialize defaults and reset the app.
%
% Args:
% app (KinematicsLab): App instance
app.Flows = struct('Label',{},'Velocity',{},'AxisLimits',{},'Streamlines',{}, ...
'UsesV0',{},'UsesOmega',{},'IsUnsteady',{});
% 1) Unsteady uniform: u=V0, v=V0 sin(ωt)
app.addFlow(struct( ...
'Label', 'Unsteady uniform: u=V0, v=V0 sin(ωt)', ...
'UsesV0', true, 'UsesOmega', true, 'IsUnsteady', true, ...
'Velocity', @(app,x,y,t) deal( ...
app.V0Field.Value + 0*x, ...
app.V0Field.Value * sin(app.OmegaField.Value*t) + 0*y), ...
'AxisLimits', @(app) axisLimitsUnsteadyUniform(app), ...
'Streamlines', @(app,tFix,n) streamlinesUniform(app,tFix,n) ...
));
% 2) Steady uniform: u=V0, v=0
app.addFlow(struct( ...
'Label', 'Steady uniform: u=V0, v=0', ...
'UsesV0', true, 'UsesOmega', false, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) deal( ...
app.V0Field.Value + 0*x, ...
0 + 0*y), ...
'AxisLimits', @(app) axisLimitsSteadyUniform(app), ...
'Streamlines', @(app,tFix,n) streamlinesUniform(app,tFix,n) ...
));
% 3) Steady saddle: u=x, v=-y
app.addFlow(struct( ...
'Label', 'Steady saddle: u=x, v=-y', ...
'UsesV0', false, 'UsesOmega', false, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) deal(x, -y), ...
'Streamlines', @(app,tFix,n) streamlinesSaddle(app,n) ...
));
% 4) Steady source: u=x, v=y
app.addFlow(struct( ...
'Label', 'Steady source: u=x, v=y', ...
'UsesV0', false, 'UsesOmega', false, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) deal(x, y), ...
'Streamlines', @(app,tFix,n) streamlinesSource(app,n) ...
));
% 5) Steady rotation: u=y, v=-x
app.addFlow(struct( ...
'Label', 'Steady rotation: u=y, v=-x', ...
'UsesV0', false, 'UsesOmega', false, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) deal(y, -x), ...
'Streamlines', @(app,tFix,n) streamlinesRotation(app,n) ...
));
% 6) Steady shear: u=V0, v=V0 x
app.addFlow(struct( ...
'Label', 'Steady shear: u=V0, v=V0 x', ...
'UsesV0', true, 'UsesOmega', false, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) deal( ...
app.V0Field.Value + 0*x, ...
app.V0Field.Value .* x), ...
'Streamlines', @(app,tFix,n) streamlinesShear(app,n) ...
));
% 7) Steady cellular: u=cos(ωx), v=sin(ωy)
app.addFlow(struct( ...
'Label', 'Steady cellular: u=cos(ωx), v=sin(ωy)', ...
'UsesV0', false, 'UsesOmega', true, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) deal( ...
cos(app.OmegaField.Value .* x), ...
sin(app.OmegaField.Value .* y)), ...
'AxisLimits', @(app) axisLimitsCellular(app), ...
'Streamlines', @(app,tFix,n) streamlinesCellular(app,tFix,n) ...
));
% 8) Steady Taylor–Green vortex (periodic cellular vortices)
app.addFlow(struct( ...
'Label', 'Steady Taylor–Green: u=sin(ωx)cos(ωy), v=-cos(ωx)sin(ωy)', ...
'UsesV0', false, 'UsesOmega', true, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) taylorGreenVel(app,x,y,t), ...
'AxisLimits', @(app) axisLimitsTaylorGreen(app), ...
'Streamlines', @(app,tFix,n) streamlinesTaylorGreen(app,tFix,n) ... % contours of ψ
));
% 9) Unsteady rotating saddle (saddle rotated by angle ωt)
app.addFlow(struct( ...
'Label', 'Unsteady rotating saddle (ωt-rotated u=x, v=-y)', ...
'UsesV0', false, 'UsesOmega', true, 'IsUnsteady', true, ...
'Velocity', @(app,x,y,t) rotatingSaddleVel(app,x,y,t), ...
'Streamlines', @(app,tFix,n) streamlinesRotatingSaddle(app,tFix,n) ... % contours of ψ
));
% 10) Steady spiral sink (focus): u=-a x - V0 y, v=V0 x - a y
app.addFlow(struct( ...
'Label', 'Steady spiral sink (focus): u=-a x - V0 y, v=V0 x - a y', ...
'UsesV0', true, 'UsesOmega', false, 'IsUnsteady', false, ...
'Velocity', @(app,x,y,t) spiralSinkVel(app,x,y,t) ...
));
% Defaults
app.ProblemDropDown.Items = {app.Flows.Label};
app.ProblemDropDown.Value = app.Flows(1).Label;
app.flowIndex = uint16(1);
app.VelCheckBox.Value = true;
app.StreamCheckBox.Value = true;
app.PathCheckBox.Value = true;
app.StreakCheckBox.Value = true;
app.V0Field.Value = 1.0;
app.X0Field.Value = 0.0;
app.Y0Field.Value = 0.0;
app.OmegaField.Value = 2;
updateOmegaEnable(app);
updateV0Enable(app);
resetAll(app);
% NESTED FUNCTIONS
function lim = axisLimitsUnsteadyUniform(app)
V0 = app.V0Field.Value;
om = app.OmegaField.Value;
x0 = app.X0Field.Value;
y0 = app.Y0Field.Value;
Vabs = abs(V0);
xMin = x0 - Vabs * max(app.TMAX, 0) - 1;
xMax = x0 + Vabs * max(app.TMAX, 0) + 1;
if abs(om) > 1e-12
A = 2 * Vabs / abs(om);
if ~isfinite(A), A = 1; end
else
A = 1;
end
yMin = y0 - 1.2 * A - 1;
yMax = y0 + 1.2 * A + 1;
lim = [xMin xMax yMin yMax];
end
function lim = axisLimitsSteadyUniform(app)
V0 = app.V0Field.Value;
x0 = app.X0Field.Value;
y0 = app.Y0Field.Value;
Vabs = abs(V0);
xMin = x0 - Vabs * max(app.TMAX, 0) - 1;
xMax = x0 + Vabs * max(app.TMAX, 0) + 1;
yMin = y0 - 4;
yMax = y0 + 4;
lim = [xMin xMax yMin yMax];
end
function lim = axisLimitsCellular(app)
om = app.OmegaField.Value;
x0 = app.X0Field.Value;
y0 = app.Y0Field.Value;
K = max(abs(om), 0.5);
L = 2*pi / K;
lim = [x0 - L, x0 + L, y0 - L, y0 + L];
end
function lim = axisLimitsTaylorGreen(app)
om = app.OmegaField.Value;
x0 = app.X0Field.Value;
y0 = app.Y0Field.Value;
k = max(abs(om), 0.5);
L = 2*pi / k; % one spatial period
half = 0.55 * L; % show ~one period with a bit of margin
lim = [x0 - half, x0 + half, y0 - half, y0 + half];
end
function [XS, YS] = streamlinesUniform(app, tFix, n)
x = linspace(app.xMin, app.xMax, 200);
[u0, v0] = app.velocity(0, 0, tFix);
slope = 0;
if abs(u0) > 1e-12
slope = v0 / u0;
end
xRef = x(1);
C = linspace(app.yMin, app.yMax, n);
XS = cell(n,1);
YS = cell(n,1);
for i = 1:n
XS{i} = x;
YS{i} = C(i) + slope * (x - xRef);
end
end
function [XS, YS] = streamlinesSaddle(app, n)
x = linspace(app.xMin, app.xMax, 200);
XS = cell(n,1);
YS = cell(n,1);
if n >= 1
XS{1} = x; YS{1} = 0*x; % y=0
end
if n >= 2
yAxis = linspace(app.yMin, app.yMax, 800);
XS{2} = 0*yAxis; YS{2} = yAxis; % x=0
end
m = max(n-2, 0);
if m > 0
Cmax = 0.35 * (max(abs([app.xMin, app.xMax])) * max(abs([app.yMin, app.yMax])) + 1);
Cvals = linspace(-Cmax, Cmax, m);
Cvals(abs(Cvals) < 1e-9) = 0.15 * Cmax;
xx = x;
epsx = 1e-6 * max(1, max(abs(x)));
xx(abs(xx) < epsx) = epsx;
for k = 1:m
i = k + 2;
XS{i} = xx;
YS{i} = Cvals(k) ./ xx; % x*y=C
end
end
for i = 1:n
if isempty(XS{i})
XS{i} = nan; YS{i} = nan;
end
end
end
function [XS, YS] = streamlinesSource(app, n)
theta = linspace(0, pi, n);
R = 1.5 * max(app.xMax - app.xMin, app.yMax - app.yMin);
r = linspace(-R, R, 1200);
XS = cell(n,1);
YS = cell(n,1);
for i = 1:n
XS{i} = r * cos(theta(i));
YS{i} = r * sin(theta(i));
end
end
function [XS, YS] = streamlinesRotation(app, n)
rMax = 0.95 * min(max(abs([app.xMin, app.xMax])), max(abs([app.yMin, app.yMax])));
rMin = max(0.15 * rMax, 0.2);
rVals = linspace(rMin, rMax, n);
th = linspace(0, 2*pi, 600);
XS = cell(n,1);
YS = cell(n,1);
for i = 1:n
XS{i} = rVals(i) * cos(th);
YS{i} = rVals(i) * sin(th);
end
end
function [XS, YS] = streamlinesShear(app, n)
x = linspace(app.xMin, app.xMax, 200);
C = linspace(app.yMin, app.yMax, n);
XS = cell(n,1);
YS = cell(n,1);
for i = 1:n
XS{i} = x;
YS{i} = 0.5 * x.^2 + C(i); % y = 0.5 x^2 + C
end
end
function [XS, YS] = streamlinesCellular(app, tFix, n)
om = app.OmegaField.Value;
% ω -> 0 limit: u=1, v=0 => streamlines are y = const
if abs(om) < 1e-12
psiFcn = @(app,X,Y,tFix) Y;
[XS, YS] = streamlinesFromPsi(app, psiFcn, tFix, n);
return
end
% "Psi" here is a FIRST INTEGRAL (invariant), not a true streamfunction.
% Streamlines satisfy: tan(ωy/2) / (sec(ωx)+tan(ωx)) = const
% We contour atan(ratio) to compress dynamic range and avoid blow-ups.
psiFcn = @(app,X,Y,tFix) cellularInvariant(app, X, Y, om);
[XS, YS] = streamlinesFromPsi(app, psiFcn, tFix, n);
function psi = cellularInvariant(app, X, Y, om) %#ok<INUSL>
wx = om .* X;
wy = om .* Y;
denom = (1 ./ cos(wx)) + tan(wx);
ratio = tan(wy/2) ./ denom; % invariant C
ratio(~isfinite(ratio)) = NaN;
% Compress range: preserves ordering/sign (ratio = tan(psi))
psi = atan(ratio);
end
end
% Streamlines via ψ contours
function [XS, YS] = streamlinesFromPsi(app, psiFcn, tFix, n)
% Streamlines as contours of streamfunction psi
% Definitions
Nx = app.numPointsStreamline;
Ny = app.numPointsStreamline;
xvec = linspace(app.xMin, app.xMax, Nx);
yvec = linspace(app.yMin, app.yMax, Ny);
[X,Y] = meshgrid(xvec, yvec);
numContoursStreamline = app.numContoursStreamline;
psi = psiFcn(app, X, Y, tFix);
psi(~isfinite(psi)) = NaN;
XS = cell(n,1);
YS = cell(n,1);
p = psi(:);
p = p(isfinite(p));
if isempty(p)
for i = 1:n, XS{i} = nan; YS{i} = nan; end
return
end
% Robust magnitude range (avoid corner outliers)
absMax = prctile(abs(p), 90);
if ~isfinite(absMax) || absMax < 1e-12
for i = 1:n, XS{i} = nan; YS{i} = nan; end
return
end
% Ensures a separatrix level even when n is even
levels = linspace(-absMax, absMax, n);
levels(round((n+1)/2)) = 0;
for i = 1:n
lev = levels(i);
C = contourc(xvec, yvec, psi, [lev lev]);
[xs, ys] = collectTopSegments(C, numContoursStreamline);
XS{i} = xs;
YS{i} = ys;
end
% NESTED FUNCTIONS
function [xs, ys] = collectTopSegments(C, numContoursStreamline)
xs = nan; ys = nan;
if isempty(C), return; end
segs = {};
lens = [];
idx = 1;
while idx < size(C,2)
npts = C(2,idx);
if idx + npts > size(C,2), break; end
seg = C(:, idx+1:idx+npts);
segs{end+1} = seg;
lens(end+1) = npts;
idx = idx + npts + 1;
end
if isempty(segs), return; end
% Keep largest segments
[~, ord] = sort(lens, 'descend');
ord = ord(1:min(numContoursStreamline, numel(ord)));
xx = [];
yy = [];
for k = 1:numel(ord)
s = segs{ord(k)};
xx = [xx, s(1,:), NaN];
yy = [yy, s(2,:), NaN];
end
% Remove trailing NaN
if ~isempty(xx)
xx(end) = [];
yy(end) = [];
end
xs = xx;
ys = yy;
end
end
function [u, v] = taylorGreenVel(app, x, y, t)
k = max(abs(app.OmegaField.Value), 0.5);
u = sin(k.*x) .* cos(k.*y);
v = -cos(k.*x) .* sin(k.*y);
end
function [XS, YS] = streamlinesTaylorGreen(app, tFix, n)
k = max(abs(app.OmegaField.Value), 0.5);
psiFcn = @(app, X, Y, tFix) sin(k.*X) .* sin(k.*Y);
[XS, YS] = streamlinesFromPsi(app, psiFcn, tFix, n);
end
function [u, v] = rotatingSaddleVel(app, x, y, t)
th = app.OmegaField.Value .* t;
c = cos(th); s = sin(th);
% Rotate coordinates: [X;Y] = R^T [x;y]
X = c.*x + s.*y;
Y = -s.*x + c.*y;
% Saddle in rotated coords: U=X, V=-Y; transform back: [u;v]=R[U;V]
u = c.*X + s.*Y;
v = s.*X - c.*Y;
end
function [XS, YS] = streamlinesRotatingSaddle(app, tFix, n)
th = app.OmegaField.Value .* tFix;
c = cos(th); s = sin(th);
psiFcn = @(app, Xg, Yg, tFix) ( (c.*Xg + s.*Yg) .* (-s.*Xg + c.*Yg) );
[XS, YS] = streamlinesFromPsi(app, psiFcn, tFix, n);
end
function [u, v] = spiralSinkVel(app, x, y, t)
V0 = app.V0Field.Value;
a = 0.25; % Decay rate
u = -a.*x - V0.*y;
v = V0.*x - a.*y;
end
end
function lim = defaultAxisLimits(app)
% Default axis limits (used when flow doesn't specify its own limits)
[x0,y0] = getX0Y0(app);
lim = [x0 - 4, x0 + 4, y0 - 4, y0 + 4];
end
%% -------------------- UI --------------------
function createComponents(app)
% Create UI layout and wire callbacks.
%
% Args:
% app (KinematicsLab): App instance
app.UIFigure = uifigure('Name', 'Kinematics', 'Color', [0.94, 0.94, 0.94]);
app.UIFigure.Position(3:4) = [900, 400];
app.UIFigure.CloseRequestFcn = @(~, ~) onClose(app);
app.UIFigure.WindowKeyPressFcn = @(src,event) onKeyPress(app, event);
gl = uigridlayout(app.UIFigure, [1, 2]);
gl.ColumnWidth = {240, '1x'};
gl.RowHeight = {'1x'};
gl.Padding = [10, 10, 10, 10];
gl.ColumnSpacing = 10;
app.LeftPanel = uipanel(gl, ...
'Title', 'Setup', ...
'BackgroundColor', [0.97, 0.97, 0.97], ...
'BorderType', 'none', ...
'FontSize', app.fontsizeLabels - 4);
app.Axes = uiaxes(gl);
configureAxesAppearance(app);
% Left-panel grid
lp = uigridlayout(app.LeftPanel, [12, 3]);
lp.Scrollable = 'on';
lp.RowHeight = {22, 22, 22, 22, 22, 22, 22, 22, 22, 12, 30, 30};
lp.ColumnWidth = {100, '1x', 50};
lp.Padding = [10, 10, 10, 10];
lp.RowSpacing = 6;
lp.ColumnSpacing = 8;
% Problem row
lbl = uilabel(lp, 'Text', 'Problem', 'HorizontalAlignment', 'left', 'FontSize', app.fontsizeLabels - 4);
lbl.Layout.Row = 1;
lbl.Layout.Column = 1;
app.ProblemDropDown = uidropdown(lp, 'ValueChangedFcn', @(~, ~) paramChanged(app), 'FontSize', app.fontsizeLabels - 4);
app.ProblemDropDown.Layout.Row = 1;
app.ProblemDropDown.Layout.Column = [2, 3];
% Velocity
app.VelCheckBox = uicheckbox(lp, 'Text', 'Velocity field', 'ValueChangedFcn', @(~, ~) toggleVisibility(app), ...
'FontSize', app.fontsizeLabels - 4);
app.VelCheckBox.Layout.Row = 2;
app.VelCheckBox.Layout.Column = [1, 2];
app.VelColorPicker = uicolorpicker(lp, 'Value', [204, 204, 204] / 255, 'ValueChangedFcn', @(~, ~) colorChanged(app));
app.VelColorPicker.Layout.Row = 2;
app.VelColorPicker.Layout.Column = 3;
% Streamline
app.StreamCheckBox = uicheckbox(lp, 'Text', 'Streamline', 'ValueChangedFcn', @(~, ~) toggleVisibility(app), ...
'FontSize', app.fontsizeLabels - 4);
app.StreamCheckBox.Layout.Row = 3;
app.StreamCheckBox.Layout.Column = [1, 2];
app.StreamColorPicker = uicolorpicker(lp, 'Value', [0.91, 0.51, 0.49], 'ValueChangedFcn', @(~, ~) colorChanged(app));
app.StreamColorPicker.Layout.Row = 3;
app.StreamColorPicker.Layout.Column = 3;
% Pathline
app.PathCheckBox = uicheckbox(lp, 'Text', 'Pathline', 'ValueChangedFcn', @(~, ~) toggleVisibility(app), ...
'FontSize', app.fontsizeLabels - 4);
app.PathCheckBox.Layout.Row = 4;
app.PathCheckBox.Layout.Column = [1, 2];
app.PathColorPicker = uicolorpicker(lp, 'Value', [89, 156, 155] / 255, 'ValueChangedFcn', @(~, ~) colorChanged(app));
app.PathColorPicker.Layout.Row = 4;
app.PathColorPicker.Layout.Column = 3;
% Streakline
app.StreakCheckBox = uicheckbox(lp, 'Text', 'Streakline', 'ValueChangedFcn', @(~, ~) toggleVisibility(app), ...
'FontSize', app.fontsizeLabels - 4);
app.StreakCheckBox.Layout.Row = 5;
app.StreakCheckBox.Layout.Column = [1, 2];
app.StreakColorPicker = uicolorpicker(lp, 'Value', [152, 209, 208] / 255, 'ValueChangedFcn', @(~, ~) colorChanged(app));
app.StreakColorPicker.Layout.Row = 5;
app.StreakColorPicker.Layout.Column = 3;
% V0
app.V0Label = uilabel(lp, 'Text', '$V_0$ [m/s]', 'HorizontalAlignment', 'left', 'FontSize', app.fontsizeLabels - 4);
app.V0Label.Interpreter = 'latex';
app.V0Label.Layout.Row = 6;
app.V0Label.Layout.Column = 1;
app.V0Field = uieditfield(lp, 'numeric', 'Value', 1.0, 'Limits', [-Inf, Inf], ...
'ValueChangedFcn', @(~, ~) paramChanged(app), 'FontSize', app.fontsizeLabels - 4);
app.V0Field.Layout.Row = 6;
app.V0Field.Layout.Column = [2, 3];
% x0
app.X0Label = uilabel(lp, 'Text', '$x_0$ [m]', 'HorizontalAlignment', 'left', 'FontSize', app.fontsizeLabels - 4);
app.X0Label.Interpreter = 'latex';
app.X0Label.Layout.Row = 7;
app.X0Label.Layout.Column = 1;
app.X0Field = uieditfield(lp, 'numeric', 'Value', 0.0, 'Limits', [-Inf, Inf], ...
'ValueChangedFcn', @(~, ~) paramChanged(app), 'FontSize', app.fontsizeLabels - 4);
app.X0Field.Layout.Row = 7;
app.X0Field.Layout.Column = [2, 3];
% y0
app.Y0Label = uilabel(lp, 'Text', '$y_0$ [m]', 'HorizontalAlignment', 'left', 'FontSize', app.fontsizeLabels - 4);
app.Y0Label.Interpreter = 'latex';
app.Y0Label.Layout.Row = 8;
app.Y0Label.Layout.Column = 1;
app.Y0Field = uieditfield(lp, 'numeric', 'Value', 0.0, 'Limits', [-Inf, Inf], ...
'ValueChangedFcn', @(~, ~) paramChanged(app), 'FontSize', app.fontsizeLabels - 4);
app.Y0Field.Layout.Row = 8;
app.Y0Field.Layout.Column = [2, 3];
% Omega
app.OmegaLabel = uilabel(lp, 'Text', '$\omega$ [1/s]', 'HorizontalAlignment', 'left', 'FontSize', app.fontsizeLabels - 4);
app.OmegaLabel.Interpreter = 'latex';
app.OmegaLabel.Layout.Row = 9;
app.OmegaLabel.Layout.Column = 1;
app.OmegaField = uieditfield(lp, 'numeric', 'Value', 2, 'Limits', [-Inf, Inf], ...
'ValueChangedFcn', @(~, ~) paramChanged(app), 'FontSize', app.fontsizeLabels - 4);
app.OmegaField.Layout.Row = 9;
app.OmegaField.Layout.Column = [2, 3];
% Buttons
btnGrid = uigridlayout(lp, [1, 2]);
btnGrid.Layout.Row = 11;
btnGrid.Layout.Column = [1, 3];
btnGrid.ColumnWidth = {'1x', '1x'};
btnGrid.RowHeight = {30};
btnGrid.Padding = [0, 0, 0, 0];
btnGrid.ColumnSpacing = 10;
app.RunButton = uibutton(btnGrid, 'Text', 'run', 'ButtonPushedFcn', @(~, ~) onRun(app), 'FontSize', app.fontsizeLabels - 4);
app.StopButton = uibutton(btnGrid, 'Text', 'stop', 'ButtonPushedFcn', @(~, ~) onStop(app), 'FontSize', app.fontsizeLabels - 4);
app.ClearButton = uibutton(lp, 'Text', 'clear', 'ButtonPushedFcn', @(~, ~) resetAll(app), 'FontSize', app.fontsizeLabels - 4);
app.ClearButton.Layout.Row = 12;
app.ClearButton.Layout.Column = [1, 3];
end
function onKeyPress(app, event)
% Ctrl+S (Windows/Linux) or Cmd+S (macOS) => snapshot
if strcmpi(event.Key, 's') && any(ismember(lower(event.Modifier), {'control','command'}))
doSnapshot(app);
end
end
function doSnapshot(app)
% Open save dialog and export the current figure as an image
% Definitions
filter = {'*.pdf';'*.jpg';'*.png';'*.tif'};
% Get the file name and path
[filename, filepath] = uiputfile(filter, 'Save snapshot as');
% Export the figure if the user did not cancel
if isequal(filename, 0) || isequal(filepath, 0)
return
end
exportapp(app.UIFigure, fullfile(filepath, filename));
end
function configureAxesAppearance(app)
% Configure axes aesthetics and LaTeX labels.
%
% Args:
% app (KinematicsLab): App instance
app.Axes.Box = 'off';
app.Axes.FontSize = app.fontsizeLabels + 2;
app.Axes.XLabel.FontSize = app.fontsizeLabels;
app.Axes.YLabel.FontSize = app.fontsizeLabels;
app.Axes.Title.FontSize = app.fontsizeLabels + 4;
app.Axes.LineWidth = 1.8;
app.Axes.TickLabelInterpreter = 'latex';
app.Axes.XLabel.Interpreter = 'latex';
app.Axes.YLabel.Interpreter = 'latex';
app.Axes.Title.Interpreter = 'latex';
app.Axes.XLabel.String = '$x$ [m]';
app.Axes.YLabel.String = '$y$ [m]';
app.Axes.XGrid = 'off';
app.Axes.YGrid = 'off';
app.Axes.XMinorGrid = 'off';
app.Axes.YMinorGrid = 'off';
updateTitle(app);
end
function onClose(app)
stopTimer(app);
delete(app);
end
function paramChanged(app)
% Callback for parameter changes (problem / V0 / x0 / y0 / omega).
% Stops simulation, resets all graphics & histories, keeps running if it was running.
wasRunning = app.isRunning;
app.flowIndex = uint16(find(strcmp(app.ProblemDropDown.Value, {app.Flows.Label}), 1, 'first'));
if isempty(app.flowIndex),
app.flowIndex = 1;
end
updateOmegaEnable(app);
updateV0Enable(app);
resetAll(app);
if wasRunning
startTimer(app);
end
end
function colorChanged(app)
updateColors(app);
end
%% ------------------ Enable/Disable parameters ------------------
function updateOmegaEnable(app)
% Enable/disable omega input depending on the selected problem
if problemUsesOmega(app)
app.OmegaField.Enable = 'on';
return
end
app.OmegaField.Enable = 'off';
end
function updateV0Enable(app)
% Enable/disable V0 input depending on the selected problem
if problemUsesV0(app)
app.V0Field.Enable = 'on';
return
end
app.V0Field.Enable = 'off';
end
function tf = problemUsesOmega(app)
% Return true if the current problem definition uses omega
%
% Returns:
% tf (logical): True if omega is used by the selected velocity field
tf = app.Flows(app.flowIndex).UsesOmega;
end
function tf = problemUsesV0(app)
% Return true if the current problem definition uses V0
%
% Returns:
% tf (logical): True if V0 is used by the selected velocity field
tf = app.Flows(app.flowIndex).UsesV0;
end
function tf = isUnsteady(app)
% Return true if the selected velocity field is time-dependent
tf = app.Flows(app.flowIndex).IsUnsteady;
end
function [x0, y0] = getX0Y0(app)
% Get initial position vector
%
% Returns:
% x0 (double): Initial x-position [m]
% y0 (double): Initial y-position [m]
x0 = app.X0Field.Value;
y0 = app.Y0Field.Value;
end
%% -------------------- Flow definition --------------------
function [u, v] = velocity(app, x, y, t)
% Evaluate the velocity field at (x, y, t)
%
% Args:
% x (double): x-position
% y (double): y-position
% t (double): time [s]
%
% Returns:
% u (double): x-velocity component at (x, y, t)
% v (double): y-velocity component at (x, y, t)
F = app.Flows(app.flowIndex);
[u, v] = F.Velocity(app, x, y, t);
end
%% -------------------- RK4 helpers --------------------
function [xn, yn] = rk4(app, x, y, t, dt)
% Advance one particle with classic RK4
%
% Args:
% x, y (double): current particle position
% t (double): current time
% dt (double): time step
%
% Returns:
% xn, yn (double): updated particle position after dt
[k1x, k1y] = app.velocity(x, y, t);
[k2x, k2y] = app.velocity(x + 0.5 * dt * k1x, y + 0.5 * dt * k1y, t + 0.5 * dt);
[k3x, k3y] = app.velocity(x + 0.5 * dt * k2x, y + 0.5 * dt * k2y, t + 0.5 * dt);
[k4x, k4y] = app.velocity(x + dt * k3x, y + dt * k3y, t + dt);
xn = x + dt * (k1x + 2 * k2x + 2 * k3x + k4x) / 6;
yn = y + dt * (k1y + 2 * k2y + 2 * k3y + k4y) / 6;
end
%% -------------------- Pathline (precompute + marker) --------------------
function precomputePathline(app)
% Precompute a pathline from t=0 using a fixed number of samples
%
% Notes:
% * This draws the pathline "to infinity" in practice by choosing
% numPointsPathline and DTPATHLINE sufficiently large/small.
% * The marker position is later interpolated from (pathT,pathX,pathY).
[x0, y0] = getX0Y0(app);
N = max(2, round(app.numPointsPathline));
dt = max(1e-4, app.DTPATHLINE);
app.pathX = nan(1, N);
app.pathY = nan(1, N);
app.pathT = nan(1, N);
app.pathX(1) = x0;
app.pathY(1) = y0;
app.pathT(1) = 0;
% Bounding box used only to decide if a zoom-out should trigger recompute.
xl = app.Axes.XLim; yl = app.Axes.YLim;
cx = mean(xl); cy = mean(yl);
rx = 1.5 * 0.5 * diff(xl);
ry = 1.5 * 0.5 * diff(yl);
app.pathBox = [cx - rx, cx + rx, cy - ry, cy + ry];