Paste #162878

   
pasted on 31.01.2021 14:42
  • Edit to this paste
  • Print
  • Raw
  • The following pastes replied to this paste:  # 276991
  • Show paste tree
  • Compare with paste
    #  
  • Toggle line numbers
  • Syntax highlighting  
Text paste
 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
import std.stdio;

extern(C) __gshared string[] rt_options =
    [ "gcopt=minPoolSize:2K maxPoolSize:1M incPoolSize:4K" ];

auto fastAbs(float x) @system
{
	uint p = *(cast(uint*) &x);
	p &=0x7fffffff;
	return *(cast(float*) &p);
}

auto renormalize(Range)(Range r)
{
	import std.algorithm;

	auto maximalAbsoluteValue = r
								.map!(a => fastAbs(a))
								.fold!max;
	return r
			.map!(a => a / maximalAbsoluteValue);
}

void main()
{
	import std.algorithm;
	import std.complex;
	import std.math;
	import std.numeric;
	import std.random;
	import std.range;

	import ppmformats;

	auto rng = Random(unpredictableSeed);

	auto signalWithNoise(float x)
	{
		return (3.3 * sin(2*x)) + uniform(-0.3, 0.3, rng);
	}
	
	alias squareWave = delegate(float x) {
	  return
          ((4 * 10) / (PI)) * (sin(x) + (sin(3 * x) / (3 * x)) + (sin(5 * x) /(5 * x)) + (sin(7 * x) / (7 * x)) + (sin(9 * x) / (9 * x)) + (sin(11 * x) / (11 * x))) + (sin(13 * x) / (13 * x)) + (sin(15 * x) / (15 * x)) + (sin(17 * x) / (17 * x));
	};

	auto signal = iota(0, 2_048)
						.map!squareWave;

	auto normalizedFFT(Range)(Range r)
	{
		return 
				r
				  .fft
				  .map!(a => 20.0f * log10(abs(a ^^ 2)))
				  .renormalize;
	}

	auto pd = signal
					.slide(1_024)
					.map!(a => normalizedFFT(a));

	auto img = new P6Image(1024, 1024);

	foreach (i, e; pd.enumerate)
	{
		foreach (j, s; e.enumerate)
		{
			img[i, j] = new RGBColor(
				cast(int) (0.8 * 255.0 * abs(s)),
				0,
				255 - cast(int) (255 * abs(s))
			);
		}
	}
	img.save(`fft.ppm`);		
}
Add Comment
Author