Alias method/别名采样方法证明和实现

算法介绍:【数学】时间复杂度O(1)的离散采样算法—— Alias method/别名采样方法

先上代码


class alias_sampling(object):
    def __init__(self,prob):
        self.n = len(prob)
        self.area_ratio = prob * self.n
        self.__create_alias_table()

    def __create_alias_table(self):
        low_indices,hight_indices = [],[]
        self.accept,self.alias = [0] * self.n,[0] * self.n
        for i,ratio in enumerate(self.area_ratio):
            if ratio < 1.0:
                low_indices.append(i)
            else:
                hight_indices.append(i)

        while low_indices and hight_indices:
            low_id,hight_id = low_indices.pop(),hight_indices[-1]
            self.accept[low_id] = self.area_ratio[low_id]
            self.alias[low_id] = hight_id
            self.area_ratio[hight_id] -= (1 - self.area_ratio[low_id])

            if self.area_ratio[hight_id] < 1.0:
                hight_indices.pop()
                low_indices.append(hight_id)

        for hight_id in hight_indices:
            self.accept[hight_id] = 1.
        for low_id in low_indices:
            self.accept[low_id] = 1.
        del self.area_ratio

    def get_sample(self):
        id = np.random.randint(0,self.n)
        if self.accept[id] > np.random.uniform(0,1):
            return id
        return self.alias[id]

    def get_samples(self,n):
        for i in range(n):
            yield self.get_sample()

def test(n=100,k=1000000):

    def gen_prop_dist(n):
        p = np.random.uniform(0,10,n)
        return p / np.sum(p)

    p = gen_prop_dist(n)
    sampling = alias_sampling(p)
    p_sample = np.zeros(n)

    for sample in sampling.get_samples(k):
        p_sample[sample] += 1

    p_sample /= k

    print(np.linalg.norm(p-p_sample,2))


if __name__ == '__main__':
    for i in range(10):
        test()

假设概率分布为 { p i } i = 0 n − 1 \{p_i\}_{i=0}^{n-1} { pi}i=0n1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
What is a DIB Section?<br>A DIB (Device Independent Bitmap) Section is a GDI object like a standard DIB but which additionally provides a pointer to the memory used to store the bitmap bits to which the creating application has direct access. This allows ultimate flexibility if you want to modify the bits of a bitmap. <br><br>Using DIB Sections<br>A DIB section is created using the GDI CreateDIBSection call. You need to modify the declare provided for this in the VB API guide because this declare assumes you cannot use the pointer to the bitmap returned by the function and simply discards it. Here are the declares you need:<br><br><br>Private Type BITMAPINFOHEADER '40 bytes <br> biSize As Long <br> biWidth As Long <br> biHeight As Long <br> biPlanes As Integer <br> biBitCount As Integer <br> biCompression As Long <br> biSizeImage As Long <br> biXPelsPerMeter As Long <br> biYPelsPerMeter As Long <br> biClrUsed As Long <br> biClrImportant As Long <br>End Type <br>Private Type BITMAPINFO <br> bmiHeader As BITMAPINFOHEADER <br> bmiColors As RGBQUAD <br>End Type <br><br>' Note - this is not the declare in the API viewer - modify lplpVoid to be <br>' Byref so we get the pointer back: <br>Private Declare Function CreateDIBSection Lib "gdi32" _ <br> (ByVal hdc As Long, _ <br> pBitmapInfo As BITMAPINFO, _ <br> ByVal un As Long, _ <br> lplpVoid As Long, _ <br> ByVal handle As Long, _ <br> ByVal dw As Long) As Long <br><br><br>To create the DIB Section, you initialise a BITMAPINFO structure with the required fields, which are all in the bmiHeader sub-structure: <br><br>Member Required Value <br>biSize Size of the BITMAPINFO structure <br>biWidth Width of the DIBSection in pixels <br><br>biHeight Height of the DIBSection in pixels <br><br>biPlanes Number of colour planes. Set to 1 <br><br>biBitCount Bits per pixel. Set to 24 for true colour <br><br>biCompression Whether to use compression. If you want to work on the bits, set this to BI_RGB so the image is uncompressed <br>biSizeImage The size of the image in bytes. This is worked out from the width, height, number of bits per pixel. In a 24 bit image there are three bytes per pixel. Additionally, GDI requires that every horizontal line in the image aligns on a four byte boundary. So for a 24 bit image the ImageSize is biWidth*biHeight*3 rounded up to the nearest four bytes. You can round up to the width to the nearest four bytes as follows:<br> (.biWidth * 3 + 3) And &HFFFFFFFC<br> <br><br><br>This allows you to create a DIB Section. You call CreateDIBSection like this: <br><br> hDib = CreateDIBSection( _ <br> lHDC, _ <br> m_tBI, _ <br> DIB_RGB_COLORS, _ <br> m_lPtr, _ <br> 0, 0) <br><br><br>Where: <br><br>hDib is a variable to receive the GDI handle to the DIB Section <br>lHDC is a valid DC, for example a Form's DC or the desktop DC<br><br>m_tBI is a the BITMAPINFO structure <br>m_lPtr is a variable to receive the pointer to the memory containing the bitmap bits. <br><br>To actually display a DIB Section, you must select it into a DC. <br><br> m_hDC = CreateCompatibleDC(0) <br> If (m_hDC <> 0) Then <br> If (CreateDIB(m_hDC, lWidth, lHeight, m_hDIb)) Then <br> m_hBmpOld = SelectObject(m_hDC, m_hDIb) <br> Create = True <br> Else <br> DeleteObject m_hDC <br> m_hDC = 0 <br> End If <br> End If <br><br><br><br>Once it is in a DC you can then use BitBlt to paint it to another device context or to transfer the contents of another device context into it. Remember you must keep track of all the handles created in GDI so you can clear them up again when the DIBSection is no longer needed. To clear up, you need to: <br><br>Select the old bitmap (m_hBmpOld) back into the DC. <br>Delete the DIB section. <br>Delete the DC. <br>So far this has created a DIB which you can load with a graphic and display on the screen, but this achieves no more than you can do with a standard bitmap. The good stuff starts when you start modifying the bitmap bits. <br><br>Modifying the Bitmap Bits Directly<br>CreateDIBSection returns an address to the memory containing the bitmap. You can manipulate this directly through VB using a cool technique to make the memory look like a VB Byte array. This technique was originally presented in VBPJ article (Note the original article is no longer easily available). It uses a hidden VB call exposed by MSVBVM50.DLL (which is also available in VB6 - thanks to Paul Wilde for pointing this out) and the ubiquitous CopyMemory call. In my opinion, “CopyMemory” is the best language feature in VB (except that it isn't VB at all!)<br><br>Here are the declares you need: <br><br>Private Type SAFEARRAY2D <br> cDims As Integer <br> fFeatures As Integer <br> cbElements As Long <br> cLocks As Long <br> pvData As Long <br> Bounds(0 To 1) As SAFEARRAYBOUND <br>End Type <br>Private Declare Function VarPtrArray Lib "msvbvm50.dll" Alias "VarPtr" (Ptr() As Any) As Long <br>Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _ <br> lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long) <br><br><br><br>To make the byte array point to the memory, you have to fill in the SAFEARRAY2D structure and then use CopyMemory as follows: <br><br>Dim tSA As SAFEARRAY2D <br>Dim bDib() As Byte <br><br> ' Get the bits in the from DIB section: <br> With tSA <br> .cbElements = 1 <br> .cDims = 2 <br> .Bounds(0).lLbound = 0 <br> ' Height of the bitmap <br> .Bounds(0).cElements = m_tBI.bmiHeader.biHeight <br> .Bounds(1).lLbound = 0 <br> ' Width of the bitmap in bits (see earlier): <br> .Bounds(1).cElements = BytesPerScanLine() <br> .pvData = m_lPtr <br> End With <br> ' Make the bDib() array point to the memory addresses: <br> CopyMemory ByVal VarPtrArray(bDib()), VarPtr(tSA), 4 <br><br><br><br>Now the bDib() array is a two dimensional array with the first dimension being the x values and the second being the y values. A 24 bit DIB section is arranged so the bytes run Blue, Green, Red and remember that since the array is padded to a DWORD boundary there may be up to three unused bytes at the end of each row. So, for example, to set the top left pixel to purple you would write this: <br><br> bDib(0,0) = 255 ' Blue <br> bDib(1, 0) = 0 ' Green <br> bDib(2, y) = 255 ' Red <br><br><br><br>Once you have finished with the bDib array, you need to be sure to clear up the SAFEARRAY pointer you have created. If you fail to do this, your code will work under Win9x but will crash NT4.0: <br><br> CopyMemory ByVal VarPtrArray(bDib), 0&, 4<br><br><br>Enough of That, I Want to Use It<br>That covers the theory of using DIB Sections. To make it easy, I include a self-contained class (cDibSection) which you can include. The implementation is as follows: <br><br>Method Description <br>BytesPerScanLine Returns the number of bytes horizontally, taking into account the bits per pixel and 4 byte boundary padding. <br>ClearUp Frees up any GDI objects held by the class. Called automatically when the class terminates. <br>CopyToClipboard Does as it says! <br>Create Creates a DIB section of the specified width and height in pixels. <br>CreateFromPicture Creates a DIB section the same size as a VB picture object and copies the bitmap in it into the DIB section. <br>DIBSectionBitsPtr Returns the address of the DIBSection's bits in memory. <br>hdc Returns the memory device context used by the class to hold the DIB Section. You can use this in GDI operations, but do not call DeleteObject on it. <br>hDib Returns a handle to the DIBSection held by the class. You can use this in GDI operations, but do not call DeleteObject on it. <br>Height Returns the Height of the DIBSection in pixels. <br>LoadPictureBlt Copies all or a part of a picture from another Device Context into the DIB section. <br>PaintPicture Similar to the VB paint picture method, this copies all or part of the DIB section to another device context using the specified Raster Operation. <br>RandomiseBits Randomises the pixels in the DIB Section, either to random colours or gray scaled. <br>Resample Resizes the DIB using linear interpolation to create a smoother resized version than you would get if you used StretchBlt. <br>Width Returns the width of the DIB in pixels. <br><br><br>A Simple Fade Example<br>This demonstrates how to fade out a bitmap. It should run as a real-time animation, provided the image size isn't too big. I've found that images which are too large don't show as a smooth animation even when the fade code runs quickly enough because BitBlt tends to "tear". This occurs because BitBlt doesn't completely display the bitmap during a single screen refresh and therefore the image is partially displayed before the refresh occurs. To get round this problem you need to use DirectX.<br><br>This sample is simplified version of the static and fade example available for download on the Image Processing using DIB Sections page.<br><br>To try this sample, create a new project and add the cDIBSection class to it. Copy the declares for CopyMemory, VarPtrArray and SAFEARRAY2D into the project's form.<br><br>Then add this sub: <br><br>Private Sub Fade( _ <br> ByRef cTo As cDIBSection, _ <br> ByVal lAmount As Long _ <br> ) <br>Dim bDib() As Byte <br>Dim x As Long, y As Long <br>Dim xMax As Long, yMax As Long <br>Dim lB As Long, lG As Long, lR As Long <br>Dim lA As Long, lA2 As Long <br>Dim lTIme As Long <br>Dim tSA As SAFEARRAY2D <br> <br> ' have the local matrix point to bitmap pixels <br> With tSA <br> .cbElements = 1 <br> .cDims = 2 <br> .Bounds(0).lLbound = 0 <br> .Bounds(0).cElements = cTo.Height <br> .Bounds(1).lLbound = 0 <br> .Bounds(1).cElements = cTo.BytesPerScanLine <br> .pvData = cTo.DIBSectionBitsPtr <br> End With <br> CopyMemory ByVal VarPtrArray(bDib), VarPtr(tSA), 4 <br> <br> yMax = cTo.Height - 1 <br> xMax = cTo.Width - 1 <br> <br> For x = 0 To (xMax * 3) Step 3 <br> For y = 0 To yMax <br> lB = lAmount * bDib(x, y) \ 255 <br> lG = lAmount * bDib(x + 1, y) \ 255 <br> lR = lAmount * bDib(x + 2, y) \ 255 <br> bDib(x, y) = lB <br> bDib(x + 1, y) = lG <br> bDib(x + 2, y) = lR <br> Next y <br> Next x <br><br> CopyMemory ByVal VarPtrArray(bDib), 0&, 4 <br> <br>End Sub <br><br><br>Add a Command Button to the Form, and put this code behind it: <br><br>Private Sub Command1_Click() <br><br>Dim cDib As New cDibSection <br>Dim cDibBuffer as New cDibSection <br>Dim i As Long <br><br> ' Load the picture to fade: <br> Set sPic = LoadPicture("Put Your File Here!") <br> cDib.CreateFromPicture sPic <br><br> ' Create a copy of it: <br> cDibBuffer.Create cDib.Width, cDib.Height <br> cDib.PaintPicture cDibBuffer.HDC <br><br> ' Fade Loop: <br> For i = 0 To 255 Step 4 <br> ' Fade the dib by amount i: <br> Fade cDib, i <br> ' Draw it: <br> cDib.PaintPicture Form1.hDC <br> ' Breathe a little. You may have to put a slowdown here: <br> DoEvents <br> ' Reset for next fade: <br> cDibBuffer.PaintPicture cDib.HDC <br> Next i <br><br>End Sub <br><br><br><br>Now run the code. When you click the button, the image will be faded as fast as your system allows. The code will run slowly in the IDE but will go much much quicker if you compile it to native code. Also, checking all the Advanced Optimisation settings will make it run about 60% faster again! On my machine (PII 266 with 8Mb Xpert@Work card) it does 40fps when working on a 256x256 pixel image. <br><br><br><br>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值