-
Notifications
You must be signed in to change notification settings - Fork 0
/
MSHA_pandas.rmd
213 lines (154 loc) · 7.96 KB
/
MSHA_pandas.rmd
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
Analysis of MSHA Inspections, Violations, and Accident Data
========================================================
_An open and ongoing analysis of the data provided by the [US Mine Safety & Health Administration](http://www.msha.gov/OpenGovernmentData/OGIMSHA.asp). See [github.com/mwfrost/MSHA](https://github.com/mwfrost/MSHA) for details._
```{r}
require(reshape)
require(plyr)
require(ggplot2)
require(lubridate)
require(xtable)
require(scales)
require(RJSONIO)
require(survival)
require(TestSurvRec)
setwd('~/Code/MSHA/')
source('./lib/calendarHeat.r')
Sys.setlocale(locale="C")
```
### Utility scripts
(not run in this process)
Download the most recent files
`.\data\msha_source\download_source.sh`
Unzip the files, replacing the old copies
`\data\msha_source\unzip_source.sh\`
Use the python `pandas` library to select and write out files small enough for R to handle gracefully.
`.\extract_wv.py`
```{r read.csv.files}
mdat <- read.csv('data/wv_mines.csv')
vdat <- read.csv('data/wv_violations.csv')
idat <- read.csv('data/wv_inspections.csv')
adat <- read.csv('data/wv_accidents.csv')
```
```{r add.dates}
mdat$current.status.dt <- mdy(as.character(mdat$CURRENT_STATUS_DT))
vdat$violation.occur.dt <- mdy(as.character(vdat$VIOLATION_OCCUR_DT))
idat$inspection.begin.dt <- ymd(gsub('-','/', gsub(' 00:00:00','',idat$INSPECTION_BEGIN_DT)))
adat$accident.dt <- ymd(gsub('-','/', gsub(' 00:00:00','',adat$ACCIDENT_DT)))
```
Every day of operation for every mine needs a record, so we can try to identify any differences between the days without accidents and those with. We don't have the full span of operating days, though. One way to fake it is to run the span between the first and last recorded inspections for each mine
```{r mine.days}
# Create an index of every day from the first inspection to the last inspection
# x is the data frame of inspections
fill.days <- function(x){
data.frame(
mine=x$MINE_ID[1],
mine.day=seq(min(x$inspection.begin.dt), max(x$inspection.begin.dt), by ="day")
)
}
mine.days <- ddply(idat, .(MINE_ID), fill.days)
mine.days$mine <- NULL
# Tests
# fill.days(idat[idat$MINE_ID==4609060,])
# by(idat[idat$MINE_ID %in% c(4609060,4601318),], idat[idat$MINE_ID %in% c(4609060,4601318),'MINE_ID'], fill.days)
```
Now that there's a unique record for every day of operation (sort of), calculate the trailing accidents, violations, and inspections for each mine/day, then join all the accident records to determine which days involved accidents.
TODO: currently ignoring the problems caused by multiple accidents per day
TODO: This step could probably be much faster as a pandas aggregation pipeline.
The following function is too slow im ddply(), and should be outsourced to pandas.
```{r trailing.events}
trailing.events <- function(mine, acc.dt=now(),trailing.days=90 ){
d <- data.frame(mine, acc.dt)
ddply(d, .(mine, acc.dt), function(x){
c(
trailing.accidents=nrow(subset(adat, MINE_ID == x$mine
& accident.dt < x$acc.dt
& accident.dt > x$acc.dt - ddays(trailing.days)
)),
trailing.violations=nrow(subset(vdat, MINE_ID == x$mine
& violation.occur.dt < x$acc.dt
& violation.occur.dt > x$acc.dt - ddays(trailing.days)
)),
trailing.injuries=sum(subset(vdat, MINE_ID == x$mine
& violation.occur.dt < x$acc.dt
& violation.occur.dt > x$acc.dt - ddays(trailing.days)
)$NO_INJURIES,na.rm = TRUE),
trailing.lost.days=sum(subset(vdat, MINE_ID == x$mine
& violation.occur.dt < x$acc.dt
& violation.occur.dt > x$acc.dt - ddays(trailing.days)
)$DAYS_LOST,na.rm = TRUE),
trailing.inspections=nrow(subset(idat, MINE_ID == x$mine
& inspection.begin.dt < x$acc.dt
& inspection.begin.dt > x$acc.dt - ddays(trailing.days)
))
)
}
)
}
# Tests
# trailing.events(c(4601318, 4601456) , ymd(c('2005-09-08', '2011-08-05')), 30)
# trailing.events(adat[1:10,'MINE_ID'], adat[1:10, 'accident.dt'], 30)
```
```{r mine.day.stats}
# head(trailing.events(mine.days[1:10,'MINE_ID'], mine.days[1:10, 'mine.day'], 30))
mine.day.stats <- trailing.events(mine.days[mine.days$MINE_ID %in% c(4609060,4601318),'MINE_ID'], mine.days[mine.days$MINE_ID %in% c(4609060,4601318), 'mine.day'], 30)
# acc.dt is now op.dt
names(mine.day.stats) <- gsub('acc.dt','op.dt', names(mine.day.stats))
mine.day.stats <- merge(mine.day.stats, adat[,c('MINE_ID','accident.dt','DEGREE_INJURY_CD','CLASSIFICATION')], by.x=c('mine','op.dt'), by.y=c('MINE_ID','accident.dt'), all.x=TRUE)
head(subset(mine.day.stats, !is.na(DEGREE_INJURY_CD)))
```
Join some useful categories to the per mine/day stats and flag accident days
```{r mine.joins}
mine.day.stats <- merge(mine.day.stats,
mdat[
,
c('MINE_ID','CURRENT_MINE_NAME','COAL_METAL_IND','CURRENT_OPERATOR_NAME','CURRENT_CONTROLLER_NAME','STATE','FIPS_CNTY_NM','NO_EMPLOYEES')
] ,
by.x=c('mine'),
by.y=c('MINE_ID')
)
mine.day.stats$bin.inj <- ifelse(is.na(mine.day.stats$DEGREE_INJURY_CD), 0, 1)
mine.day.stats$bin.acc <- ifelse(is.na(mine.day.stats$CLASSIFICATION), 0, 1)
head(subset(mine.day.stats, p.acc==1.0))
```
```{r two.mine.plot}
table(mine.day.stats$CLASSIFICATION)
ggplot(mine.day.stats) +
geom_segment(data=
mine.day.stats[
mine.day.stats$bin.acc==1.0 & grepl('FIRE |IGNITION', mine.day.stats$CLASSIFICATION)
,
]
, aes(x=op.dt,xend=op.dt, y=150, yend=0),color='yellow') +
geom_line(aes(x=op.dt,y=trailing.violations)) +
geom_line(aes(x=op.dt,y=trailing.accidents),color='red') +
geom_line(aes(x=op.dt,y=trailing.inspections),color='blue') +
facet_grid(CURRENT_MINE_NAME~.)
ggplot(mine.day.stats) +
geom_point(aes(x=trailing.accidents,y=trailing.violations)) + stat_smooth(aes(x=trailing.accidents,y=trailing.violations))
ggplot(mine.day.stats[mine.day.stats$mine==4601318, ]) + geom_line(aes(x=op.dt, y=trailing.violations), color='red')
```
Trying the `glm` library's logit model
```{r logit}
logit.acc <- glm(bin.acc ~ trailing.violations + trailing.accidents, data = mine.day.stats, family = "binomial")
summary(logit.acc)
confint(logit.acc)
mine.day.stats$pred.acc <- predict(logit.acc, mine.day.stats[,c('trailing.violations','trailing.accidents')])
ggplot(mine.day.stats) + geom_point(aes(x=trailing.violations, y=pred.acc, color=trailing.accidents))
```
Survival analysis approach
Data format explained [here](http://stats.stackexchange.com/questions/59636/how-do-you-prepare-longitudinal-data-for-survival-analysis)
Instead of day-by-day records, calculate accident-free periods with start and end dates, and assign a status of 1 for each accident
```{r survival}
# transform accident records into periods
# each accident is the end date of a period, and the preceding accident is the maximum date less than it
periods <-data.frame(
MINE_ID=adat$MINE_ID,
tstop =adat$accident.dt)
periods <- ddply(periods, .(MINE_ID, tstop), function(x) c(status=1, tstart=max(periods[periods$MINE_ID==x$MINE_ID & periods$tstop < x$tstop,'tstop'])))
periods$time <- as.numeric(periods$tstop - periods$tstart)/(3600*24)
periods$time <- ifelse(IsInf(periods$time), NULL, periods$time)
periods$time <- ifelse(is.infinite(periods$time), NA, periods$time)
periods$id <- periods$MINE_ID
plot(survfit(Surv(time, status) ~ 1, data=periods[periods$id %in% periods[1:20,'id'],] ),
conf.int=FALSE, mark.time=FALSE)
```