Анализ шума прокатного стана (Учебный датасет)
Автор
using DataFrames, CSV, XLSX, Random, Dates, Statistics
"""
write_wav_pcm16(path, signal, fs)
Сохраняет моно-сигнал в PCM16 WAV без внешних зависимостей.
"""
function write_wav_pcm16(path::AbstractString, signal::AbstractVector{<:Real}, fs::Int)
samples = Int16.(round.(clamp.(Float64.(signal), -1, 1) .* 32767))
n = length(samples)
datasize = n * 2
open(path, "w") do io
write(io, UInt8.(['R','I','F','F']))
write(io, UInt32(36 + datasize))
write(io, UInt8.(['W','A','V','E']))
write(io, UInt8.(['f','m','t',' ']))
write(io, UInt32(16)) # PCM chunk size
write(io, UInt16(1)) # PCM format
write(io, UInt16(1)) # mono
write(io, UInt32(fs))
write(io, UInt32(fs * 2)) # byte rate
write(io, UInt16(2)) # block align
write(io, UInt16(16)) # bits per sample
write(io, UInt8.(['d','a','t','a']))
write(io, UInt32(datasize))
for s in samples
write(io, s)
end
end
end
"""
generate_sensor_readings(; n_days=90, readings_per_day=24, missing_prob=0.05,
temp_base=25.0, temp_amplitude=5.0, vibration_base=0.1,
vibration_amplitude=0.05, current_base=50.0, current_amplitude=10.0,
seed=42)
Генерирует регулярные показания датчиков прокатного стана (температура, вибрация, ток)
с суточной/сезонной динамикой, деградацией вибрации и пропусками.
"""
function generate_sensor_readings(;
n_days::Int=90,
readings_per_day::Int=24,
missing_prob::Float64=0.05,
temp_base::Float64=25.0,
temp_amplitude::Float64=5.0,
vibration_base::Float64=0.1,
vibration_amplitude::Float64=0.05,
current_base::Float64=50.0,
current_amplitude::Float64=10.0,
seed::Int=42
)
Random.seed!(seed)
start_date = Date(2024, 1, 1)
n_points = n_days * readings_per_day
timestamps = [DateTime(start_date + Day(d)) + Hour(h)
for d in 0:n_days-1 for h in 0:readings_per_day-1]
temp = temp_base .+ temp_amplitude * sin.(2π * (1:n_points) / readings_per_day) .+
2.0 * sin.(2π * (1:n_points) / (n_points / 2)) .+ 0.5 * randn(n_points)
degradation = 0.001 * (1:n_points) .+ 0.01 * randn(n_points)
vibration = vibration_base .+ vibration_amplitude * sin.(2π * 0.1 * (1:n_points)) .+ degradation
current = current_base .+ current_amplitude * sin.(2π * (1:n_points) / readings_per_day) .+
0.5 * temp .+ 2 * randn(n_points)
missing_mask = rand(n_points) .< missing_prob
temp[missing_mask] .= NaN
vibration[missing_mask] .= NaN
current[missing_mask] .= NaN
DataFrame(
timestamp = timestamps,
temperature = temp,
vibration = vibration,
current = current,
day = [d for d in 0:n_days-1 for _ in 0:readings_per_day-1],
hour = [h for _ in 0:n_days-1 for h in 0:readings_per_day-1]
)
end
"""
generate_audio_recordings(; n_recordings=50, fs=10000, duration=1.0,
output_dir, seed=42)
Генерирует аудиозаписи вибрации подшипников прокатного стана (WAV)
для состояний: normal, inner, outer, roller.
"""
function generate_audio_recordings(;
n_recordings::Int=50,
fs::Int=10000,
duration::Float64=1.0,
output_dir::AbstractString,
seed::Int=42
)
Random.seed!(seed)
mkpath(output_dir)
t = collect(0:1/fs:duration-1/fs)
n = length(t)
normal = 0.5 * sin.(2π * 50 .* t) .+ 0.1 * randn(n)
inner_defect = 0.8 * sin.(2π * 55 .* t) .+ 0.3 * sin.(2π * 110 .* t) .+ 0.2 * randn(n)
outer_defect = 0.9 * sin.(2π * 45 .* t) .+ 0.3 * sin.(2π * 90 .* t) .+ 0.2 * randn(n)
roller_defect = 0.7 * sin.(2π * 60 .* t) .+ 0.3 * sin.(2π * 120 .* t) .+ 0.2 * randn(n)
states = Dict(
"normal" => normal,
"inner" => inner_defect,
"outer" => outer_defect,
"roller" => roller_defect
)
recordings = NamedTuple[]
start_date = DateTime(2024, 1, 1)
for i in 1:n_recordings
timestamp = start_date + Day(rand(0:90)) + Hour(rand(8:20)) + Minute(rand(0:59))
state_name = rand() < 0.3 ? rand(["inner", "outer", "roller"]) : "normal"
signal = copy(states[state_name])
mx = maximum(abs.(signal))
if mx > 0
signal = signal / mx * 0.9
end
filename = "bearing_$(lpad(string(i), 3, '0'))_$(state_name)_$(Dates.format(timestamp, "yyyymmdd_HHMMSS")).wav"
filepath = joinpath(output_dir, filename)
write_wav_pcm16(filepath, signal, fs)
push!(recordings, (
recording_id = i,
timestamp = timestamp,
state_name = state_name,
audio_file = filename,
day = Dates.dayofyear(timestamp),
hour = Dates.hour(timestamp)
))
end
DataFrame(recordings)
end
"""
generate_rolling_mill_sensors_audio(; n_days=90, readings_per_day=24,
n_recordings=50, seed=42, outdir=@__DIR__)
Генерирует датасет сенсоров и аудиозаписей прокатного стана:
- sensor_readings.csv/.xlsx — регулярные показания (температура, вибрация, ток)
- audio_recordings.csv/.xlsx — метаданные аудиозамеров
- audio/*.wav — аудиозаписи вибрации подшипников
"""
function generate_rolling_mill_sensors_audio(;
n_days::Int=90,
readings_per_day::Int=24,
n_recordings::Int=50,
seed::Int=42,
outdir::AbstractString=@__DIR__
)
mkpath(outdir)
audio_dir = joinpath(outdir, "audio")
mkpath(audio_dir)
sensor_df = generate_sensor_readings(
n_days=n_days, readings_per_day=readings_per_day, seed=seed
)
audio_df = generate_audio_recordings(
n_recordings=n_recordings, output_dir=audio_dir, seed=seed + 100
)
CSV.write(joinpath(outdir, "sensor_readings.csv"), sensor_df)
XLSX.writetable(joinpath(outdir, "sensor_readings.xlsx"),
collect(eachcol(sensor_df)), names(sensor_df); sheetname="sensors", overwrite=true)
CSV.write(joinpath(outdir, "audio_recordings.csv"), audio_df)
XLSX.writetable(joinpath(outdir, "audio_recordings.xlsx"),
collect(eachcol(audio_df)), names(audio_df); sheetname="audio", overwrite=true)
println("sensor_readings: ", nrow(sensor_df), " строк")
println("audio_recordings: ", nrow(audio_df), " записей")
println("audio files: ", length(readdir(audio_dir)))
return (sensor=sensor_df, audio=audio_df)
end
if abspath(PROGRAM_FILE) == @__FILE__
generate_rolling_mill_sensors_audio()
end