Category Archives: R

Simulating a wind speed time series in python

I needed to generate a wind speed time series for a simulation, and couldn’t find any pre-existing code in Python to achieve this.

However, I did find the following post on using a Markov autoregressive function to achieve the same in R:

http://procomun.wordpress.com/2010/11/02/how-to-simulate-wind-speed-time-series-with-r/

So I’ve copied the mathematics used there and ported it across to Python, but with a bit of OOP rearrangement to give an object which will compute values on demand. In retrospect, a full-on generator class might be more pythonic, but I’ll leave that for now.

First some imports and helper functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
import datetime
import math
import numpy
import random
import operator
from collections import Counter

#homegrown weibull probability function
#scipy.stats.exonweib.pdf gives different result from R dweibull function
def weibullpdf(data,scale,shape):
    return [(shape/scale)*((x/scale)**(shape-1))*math.exp(-1*(x/scale)**shape) for x in data]
   
#matrix-vector multiplier from http://code.activestate.com/recipes/121574-matrix-vector-multiplication/
#equivalent to %*% in R
def matmult4(m, v):
    return [reduce(operator.add,map(operator.mul,r,v)) for r in m]

Read more …