My OLED display just stays completely white - esp32

I am programming an ESP32 with Micropython and Thonny IDE.
I upload the following SSD1306 driver library:
#MicroPython SSD1306 OLED driver, I2C and SPI interfaces created by Adafruit
import time
import framebuf
# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xa4)
SET_NORM_INV = const(0xa6)
SET_DISP = const(0xae)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xa0)
SET_MUX_RATIO = const(0xa8)
SET_COM_OUT_DIR = const(0xc0)
SET_DISP_OFFSET = const(0xd3)
SET_COM_PIN_CFG = const(0xda)
SET_DISP_CLK_DIV = const(0xd5)
SET_PRECHARGE = const(0xd9)
SET_VCOM_DESEL = const(0xdb)
SET_CHARGE_PUMP = const(0x8d)
class SSD1306:
def __init__(self, width, height, external_vcc):
self.width = width
self.height = height
self.external_vcc = external_vcc
self.pages = self.height // 8
# Note the subclass must initialize self.framebuf to a framebuffer.
# This is necessary because the underlying data buffer is different
# between I2C and SPI implementations (I2C needs an extra byte).
self.poweron()
self.init_display()
def init_display(self):
for cmd in (
SET_DISP | 0x00, # off
# address setting
SET_MEM_ADDR, 0x00, # horizontal
# resolution and layout
SET_DISP_START_LINE | 0x00,
SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0
SET_MUX_RATIO, self.height - 1,
SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0
SET_DISP_OFFSET, 0x00,
SET_COM_PIN_CFG, 0x02 if self.height == 32 else 0x12,
# timing and driving scheme
SET_DISP_CLK_DIV, 0x80,
SET_PRECHARGE, 0x22 if self.external_vcc else 0xf1,
SET_VCOM_DESEL, 0x30, # 0.83*Vcc
# display
SET_CONTRAST, 0xff, # maximum
SET_ENTIRE_ON, # output follows RAM contents
SET_NORM_INV, # not inverted
# charge pump
SET_CHARGE_PUMP, 0x10 if self.external_vcc else 0x14,
SET_DISP | 0x01): # on
self.write_cmd(cmd)
self.fill(0)
self.show()
def poweroff(self):
self.write_cmd(SET_DISP | 0x00)
def contrast(self, contrast):
self.write_cmd(SET_CONTRAST)
self.write_cmd(contrast)
def invert(self, invert):
self.write_cmd(SET_NORM_INV | (invert & 1))
def show(self):
x0 = 0
x1 = self.width - 1
if self.width == 64:
# displays with width of 64 pixels are shifted by 32
x0 += 32
x1 += 32
self.write_cmd(SET_COL_ADDR)
self.write_cmd(x0)
self.write_cmd(x1)
self.write_cmd(SET_PAGE_ADDR)
self.write_cmd(0)
self.write_cmd(self.pages - 1)
self.write_framebuf()
def fill(self, col):
self.framebuf.fill(col)
def pixel(self, x, y, col):
self.framebuf.pixel(x, y, col)
def scroll(self, dx, dy):
self.framebuf.scroll(dx, dy)
def text(self, string, x, y, col=1):
self.framebuf.text(string, x, y, col)
class SSD1306_I2C(SSD1306):
def __init__(self, width, height, i2c, addr=0x3c, external_vcc=False):
self.i2c = i2c
self.addr = addr
self.temp = bytearray(2)
# Add an extra byte to the data buffer to hold an I2C data/command byte
# to use hardware-compatible I2C transactions. A memoryview of the
# buffer is used to mask this byte from the framebuffer operations
# (without a major memory hit as memoryview doesn't copy to a separate
# buffer).
self.buffer = bytearray(((height // 8) * width) + 1)
self.buffer[0] = 0x40 # Set first byte of data buffer to Co=0, D/C=1
self.framebuf = framebuf.FrameBuffer1(memoryview(self.buffer)[1:], width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.temp[0] = 0x80 # Co=1, D/C#=0
self.temp[1] = cmd
self.i2c.writeto(self.addr, self.temp)
def write_framebuf(self):
# Blast out the frame buffer using a single I2C transaction to support
# hardware I2C interfaces.
self.i2c.writeto(self.addr, self.buffer)
def poweron(self):
pass
class SSD1306_SPI(SSD1306):
def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):
self.rate = 10 * 1024 * 1024
dc.init(dc.OUT, value=0)
res.init(res.OUT, value=0)
cs.init(cs.OUT, value=1)
self.spi = spi
self.dc = dc
self.res = res
self.cs = cs
self.buffer = bytearray((height // 8) * width)
self.framebuf = framebuf.FrameBuffer1(self.buffer, width, height)
super().__init__(width, height, external_vcc)
def write_cmd(self, cmd):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.low()
self.cs.low()
self.spi.write(bytearray([cmd]))
self.cs.high()
def write_framebuf(self):
self.spi.init(baudrate=self.rate, polarity=0, phase=0)
self.cs.high()
self.dc.high()
self.cs.low()
self.spi.write(self.buffer)
self.cs.high()
def poweron(self):
self.res.high()
time.sleep_ms(1)
self.res.low()
time.sleep_ms(10)
self.res.high()
And the following code:
# Complete project details at https://RandomNerdTutorials.com
from machine import Pin, SoftI2C
import ssd1306
from time import sleep
# ESP32 Pin assignment
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Hello, World 1!', 0, 0)
oled.text('Hello, World 2!', 0, 10)
oled.text('Hello, World 3!', 0, 20)
oled.show()
But my OLED display just stays full white, with random pixels.
Display full white
Obs: I am using a 1.3" 128x64 OLED display bought in Aliexpress
Display

Related

ImportError: can't import name InvalidChecksum

in raspberry pi pico board when i tried to connect 3v3 with 3v3 of raspberry pi pico , gnd to gnd of raspberry pi pico and dat to g16 and ran this belo code on thonny micropython .
main temp_hum_DHT_code.py
from machine import Pin
import time
from dht import DHT11, InvalidChecksum
sensor = DHT11(Pin(16, Pin.OUT, Pin.PULL_DOWN))
while True:
temp = sensor.temperature
humidity = sensor.humidity
print("Temperature: {}°C Humidity: {:.0f}% ".format(temp, humidity))
time.sleep(2)
dht.py
import array
import micropython
import utime
from machine import Pin
from micropython import const
class InvalidChecksum(Exception):
pass
class InvalidPulseCount(Exception):
pass
MAX_UNCHANGED = const(100)
MIN_INTERVAL_US = const(200000)
HIGH_LEVEL = const(50)
EXPECTED_PULSES = const(84)
class DHT11:
_temperature: float
_humidity: float
def __init__(self, pin):
self._pin = pin
self._last_measure = utime.ticks_us()
self._temperature = -1
self._humidity = -1
def measure(self):
current_ticks = utime.ticks_us()
if utime.ticks_diff(current_ticks, self._last_measure) < MIN_INTERVAL_US and (
self._temperature > -1 or self._humidity > -1
):
# Less than a second since last read, which is too soon according
# to the datasheet
return
self._send_init_signal()
pulses = self._capture_pulses()
buffer = self._convert_pulses_to_buffer(pulses)
self._verify_checksum(buffer)
self._humidity = buffer[0] + buffer[1] / 10
self._temperature = buffer[2] + buffer[3] / 10
self._last_measure = utime.ticks_us()
#property
def humidity(self):
self.measure()
return self._humidity
#property
def temperature(self):
self.measure()
return self._temperature
def _send_init_signal(self):
self._pin.init(Pin.OUT, Pin.PULL_DOWN)
self._pin.value(1)
utime.sleep_ms(50)
self._pin.value(0)
utime.sleep_ms(18)
#micropython.native
def _capture_pulses(self):
pin = self._pin
pin.init(Pin.IN, Pin.PULL_UP)
val = 1
idx = 0
transitions = bytearray(EXPECTED_PULSES)
unchanged = 0
timestamp = utime.ticks_us()
while unchanged < MAX_UNCHANGED:
if val != pin.value():
if idx >= EXPECTED_PULSES:
raise InvalidPulseCount(
"Got more than {} pulses".format(EXPECTED_PULSES)
)
now = utime.ticks_us()
transitions[idx] = now - timestamp
timestamp = now
idx += 1
val = 1 - val
unchanged = 0
else:
unchanged += 1
pin.init(Pin.OUT, Pin.PULL_DOWN)
if idx != EXPECTED_PULSES:
raise InvalidPulseCount(
"Expected {} but got {} pulses".format(EXPECTED_PULSES, idx)
)
return transitions[4:]
def _convert_pulses_to_buffer(self, pulses):
"""Convert a list of 80 pulses into a 5 byte buffer
The resulting 5 bytes in the buffer will be:
0: Integral relative humidity data
1: Decimal relative humidity data
2: Integral temperature data
3: Decimal temperature data
4: Checksum
"""
# Convert the pulses to 40 bits
binary = 0
for idx in range(0, len(pulses), 2):
binary = binary << 1 | int(pulses[idx] > HIGH_LEVEL)
# Split into 5 bytes
buffer = array.array("B")
for shift in range(4, -1, -1):
buffer.append(binary >> shift * 8 & 0xFF)
return buffer
def _verify_checksum(self, buffer):
# Calculate checksum
checksum = 0
for buf in buffer[0:4]:
checksum += buf
if checksum & 0xFF != buffer[4]:
raise InvalidChecksum()
.............................................................................................................................................................

How we can explain below validation loss?

I have trained different number of layers in CNN+LSTM encoder and decoder model with attention.
The problem I am facing is very strange to me. The validation loss is fluctuating around 3.***. As we can see from the below loss graphs. I have 3 CNN layer+1 layer BLSTM at encoder and 1 LSTM at decoder
3 layer CNN+2 layers of BLSTM at encoder and 1 layer LSTM at encoder
I have also tried weight decay from 0.1 to 0.000001. But still I am getting this type of loss graphs. Note that the Accuracy of the model is increasing on both validation and trainset. How is it possible that validation loss is still around 3 but accuracy is increasing? Can someone explain this?
Thanks
`
class Encoder(nn.Module):
def init(self,height, width, enc_hid_dim, dec_hid_dim, dropout):
super().init()
self.height= height
self.enc_hid_dim=enc_hid_dim
self.width=width
self.layer0 = nn.Sequential(
nn.Conv2d(1, 8, kernel_size=(3,3),stride =(1,1), padding=1),
nn.ReLU(),
nn.BatchNorm2d(8),
nn.MaxPool2d(2,2),
)
self.layer1 = nn.Sequential(
nn.Conv2d(8, 32, kernel_size=(3,3),stride =(1,1), padding=1),
nn.ReLU(),
nn.BatchNorm2d(32),
nn.MaxPool2d(2,2),
)
self.layer2 = nn.Sequential(
nn.Conv2d(32, 64, kernel_size=(3,3),stride =(1,1), padding=1),
nn.ReLU(),
nn.BatchNorm2d(64),
nn.MaxPool2d(2,2)
)
self.rnn = nn.LSTM(self.height//8*64, self.enc_hid_dim, bidirectional=True)
self.fc = nn.Linear(enc_hid_dim * 2, dec_hid_dim)
self.dropout = nn.Dropout(dropout)
self.cnn_dropout = nn.Dropout(p=0.2)
def forward(self, src, in_data_len, train):
batch_size = src.shape[0]
out = self.layer0(src)
out = self.layer1(out)
out = self.layer2(out)
out = self.dropout(out) # torch.Size([batch, channel, h, w])
out = out.permute(3, 0, 2, 1) # (width, batch, height, channels)
out.contiguous()
out = out.reshape(-1, batch_size, self.height//8*64) #(w,batch, (height, channels))
width = out.shape[0]
src_len = in_data_len.numpy()*(width/self.width)
src_len = src_len + 0.999 # in case of 0 length value from float to int
src_len = src_len.astype('int')
out = pack_padded_sequence(out, src_len.tolist(), batch_first=False)
outputs, hidden_out = self.rnn(out)
hidden=hidden_out[0]
cell=hidden_out[1]
# output: t, b, f*2 hidden: 2, b, f
outputs, output_len = pad_packed_sequence(outputs, batch_first=False)
hidden = torch.tanh(self.fc(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1)))
cell = torch.tanh(self.fc(torch.cat((cell[-2,:,:], cell[-1,:,:]), dim = 1)))
return outputs, hidden, cell, output_len
class Decoder(nn.Module):
def init(self, output_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout, attention):
super().init()
self.output_dim = output_dim
self.attention = attention
self.embedding = nn.Embedding(output_dim, emb_dim)
self.rnn = nn.LSTM((enc_hid_dim * 2) + emb_dim, dec_hid_dim)
self.fc_out = nn.Linear((enc_hid_dim * 2) + dec_hid_dim + emb_dim, output_dim)
self.dropout_layer = nn.Dropout(dropout)
def forward(self, input, hidden, cell, encoder_outputs, train):
input=torch.topk(input,1)[1]
embedded = self.embedding(input)
if train:
embedded=self.dropout_layer(embedded)
embedded = embedded.permute(1, 0, 2)
#embedded = [1, batch size, emb dim]
a = self.attention(hidden, encoder_outputs)
#a = [batch size, src len]
a = a.unsqueeze(1)
#a = [batch size, 1, src len]
encoder_outputs = encoder_outputs.permute(1, 0, 2)
#encoder_outputs = [batch size, src len, enc hid dim * 2]
weighted = torch.bmm(a, encoder_outputs)
weighted = weighted.permute(1, 0, 2)
#weighted = [1, batch size, enc hid dim * 2]
rnn_input = torch.cat((embedded, weighted), dim = 2)
output, hidden_out = self.rnn(rnn_input (hidden.unsqueeze(0),cell.unsqueeze(0)))
hidden=hidden_out[0]
cell=hidden_out[1]
assert (output == hidden).all()
embedded = embedded.squeeze(0)
output = output.squeeze(0)
weighted = weighted.squeeze(0)
prediction = self.fc_out(torch.cat((output, weighted, embedded), dim = 1))
return prediction, hidden.squeeze(0), cell.squeeze(0)
`

AM2320 Sensor: CRCs doesn't match, CRC from sensor(0)

Note: Code is cross-compiled in windows 10.
Code:
package main
import (
"fmt"
"io"
"log"
"net/http"
aosong "github.com/d2r2/go-aosong"
i2c "github.com/d2r2/go-i2c"
)
const i2CAddress = 0x5c
const i2CBus = 1
// Server struct
type Server struct {
Sensor *aosong.Sensor
I2C *i2c.I2C
}
func main() {
var err error
s := Server{Sensor: aosong.NewSensor(aosong.AM2320)}
s.I2C, err = i2c.NewI2C(i2CAddress, i2CBus)
if err != nil {
log.Printf(err.Error())
}
fmt.Println(s.Sensor.ReadRelativeHumidityAndTemperature(s.I2C))
defer s.I2C.Close()
}
Debug info:
2019-02-12T10:29:19.692 [ i2c] DEBUG Write 3 hex bytes: [030004]
2019-02-12T10:29:19.697 [ i2c] DEBUG Read 8 hex bytes: [0304012500d92045]
2019-02-12T10:29:19.698 [ i2c] DEBUG Read 8 hex bytes: [0000000000000000]
CRCs doesn't match: CRC from sensor(0) != calculated CRC(6912).
Any ideea why the CRC from sensor is 0?
I am able to read the sensor on the same bus with the same address with a python script.
#!/usr/bin/python
import posix
from fcntl import ioctl
import time
class AM2320:
I2C_ADDR = 0x5c
I2C_SLAVE = 0x0703
def __init__(self, i2cbus = 1):
self._i2cbus = i2cbus
#staticmethod
def _calc_crc16(data):
crc = 0xFFFF
for x in data:
crc = crc ^ x
for bit in range(0, 8):
if (crc & 0x0001) == 0x0001:
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc
#staticmethod
def _combine_bytes(msb, lsb):
return msb << 8 | lsb
def readSensor(self):
fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR)
ioctl(fd, self.I2C_SLAVE, self.I2C_ADDR)
# wake AM2320 up, goes to sleep to not warm up and affect the humidity sensor
# This write will fail as AM2320 won't ACK this write
try:
posix.write(fd, b'\0x00')
except:
pass
time.sleep(0.001) #Wait at least 0.8ms, at most 3ms
# write at addr 0x03, start reg = 0x00, num regs = 0x04 */
posix.write(fd, b'\x03\x00\x04')
time.sleep(0.0016) #Wait at least 1.5ms for result
# Read out 8 bytes of result data
# Byte 0: Should be Modbus function code 0x03
# Byte 1: Should be number of registers to read (0x04)
# Byte 2: Humidity msb
# Byte 3: Humidity lsb
# Byte 4: Temperature msb
# Byte 5: Temperature lsb
# Byte 6: CRC lsb byte
# Byte 7: CRC msb byte
data = bytearray(posix.read(fd, 8))
# Check data[0] and data[1]
if data[0] != 0x03 or data[1] != 0x04:
raise Exception("First two read bytes are a mismatch")
# CRC check
if self._calc_crc16(data[0:6]) != self._combine_bytes(data[7], data[6]):
raise Exception("CRC failed")
# Temperature resolution is 16Bit,
# temperature highest bit (Bit15) is equal to 1 indicates a
# negative temperature, the temperature highest bit (Bit15)
# is equal to 0 indicates a positive temperature;
# temperature in addition to the most significant bit (Bit14 ~ Bit0)
# indicates the temperature sensor string value.
# Temperature sensor value is a string of 10 times the
# actual temperature value.
temp = self._combine_bytes(data[4], data[5])
if temp & 0x8000:
temp = -(temp & 0x7FFF)
temp /= 10.0
humi = self._combine_bytes(data[2], data[3]) / 10.0
return (temp, humi)
am2320 = AM2320(1)
(t,h) = am2320.readSensor()
print t, h
Seems there was an issue with the library itself which was making two reads, but because the read code was not sent the values came as 0, as it can be seen in the logs:
2019-02-12T10:29:19.692 [ i2c] DEBUG Write 3 hex bytes: [030004]
2019-02-12T10:29:19.697 [ i2c] DEBUG Read 8 hex bytes: [0304012500d92045] (first read that was ignored)
2019-02-12T10:29:19.698 [ i2c] DEBUG Read 8 hex bytes: [0000000000000000] (second one that came a 0)
CRCs doesn't match: CRC from sensor(0) != calculated CRC(6912)
Made a PR to fix the issue: https://github.com/d2r2/go-aosong/pull/3

How to understand .bitmap format encoding. Convert 1-bit bitmaps to images by pen-and-paper

I'm struggling to interpret and make-sense of the many bitmap format options, and my use case is so simple that I was hoping someone could point me in the right direction: how do I (mentally, with pen-and-paper) convert a raw .bitmap file to an array of pixels? All the other sites I could find either give a function or library to solve the problem computationally, or I can't understand the fine distinctions between the various formatting options (as well as my confusion between .bmp and .bitmap).
My image was drawn with a "13 X 11" pixel grid in GIMP, with index model set to 1-bit before being exported at a .bitmap file. The file is copied below, along with two ASCII representations of it: you should be able to see "73" in the middle along with some pixels on the top and bottom row in the pattern: 1101001000010.
#define seventythree_with_fibbonacci_spaces_pixels_width 13
#define seventythree_with_fibbonacci_spaces_pixels_height 11
static unsigned char seventythree_with_fibbonacci_spaces_pixels_bits[] = {
0x4b, 0x08, 0x3e, 0x07, 0xa0, 0x04, 0x30, 0x04, 0x10, 0x07, 0x18, 0x04,
0x0c, 0x04, 0x84, 0x04, 0x84, 0x03, 0x00, 0x00, 0x4b, 0x08 };
/*
1101001000010
0111110011100
0000010100100
0000110000100
0000100011100
0001100000100
0011000000100
0010000100100
0010000111000
0000000000000
1101001000010
*/
/*
## # # #
##### ###
# # #
## #
# ###
## #
## #
# # #
# ###
## # # #
*/
// where a 1 or # represents a black pixel square,
// and a 0 or space is a white/blank square.
Now my question is: what is the exact mathematical relationship between those 22 8-bit words [75, 8, 62, ...., 75, 8] and the original picture that I draw in GIMP?
I want to be able to draw simple images in GIMP, convert it to a plain grid or array of bits/bools, and then I can use that array to redraw the picture in a totally different context (video game maps to be precise, with the black pixels mapping to, e.g., walls).
I believe I solved it now: see this python script (I commented heavily, I know that's kind of a marmite decision for some people!). I was using python3 (3.6.5)
from sys import argv # argument values
from math import ceil
"""
In GIMP, draw a WIDTH x HEIGHT Black & White picture:: Image/Mode >> Indexed...<use black and white (1 Bit) palette>:: export as .bitmap and choose the X10 format option.
This script can draw a simple ASCII image of it, or be used to get a binary
For testing, I used:
python3 convertBitMapX10_to_binary_grid.py Lev1_TD.bitmap
"""
if len(argv) > 2:
saveFileName = argv[2]
else:
saveFileName = "image_dump"
f = open(argv[1], "r")
l = [line for line in f.readlines()]
f.close()
## print(l[0])
## print(l[1])
## print(l[2])
# print(l[3])
# print(l[4])
WIDTH = int(l[0].split()[-1])
HEIGHT = int(l[1].split()[-1])
# l[3:] is our plan
l = l[3:] # lines 0 and 1 were only useful for getting the image width (x) and height (y)
# line 2 is just "static unsigned short Lev1_TD_bits[] = {"
# print([l[-1]])
# [' 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x000f };\n']
l[-1] = l[-1].strip()[:-3]
# print(l[-1])
l = [line.strip() for line in l]
# print(l[0]) #0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x000f, 0xffff, 0xffff,
# print(l[-1]) #0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x000f
l[-1] = l[-1] + ","
# Now every line has the same format (although l[-1] may have fewer elements)
#print(len(l[0])) #71
#print(len(l[2])) #71
#print(len(l[7])) #71
#print(len(l[-1])) #55
### NOTICE ALL OF THESE ARE === -1 IN MODULO 8 -- that's because they are missing a ' ' char at the end
# (8 == len("0xffff, "), if you wondered where '8' came from)
l = [line + " " for line in l]
l = [line.split(", ")[:-1] for line in l]
# l is now a list of lists. most of these lists have lengths of 72/8 (9), except the last, which has 7
# the elements of each of these sublists is a string like "0xffff" or "0x0000"
## the '[:-1]' clause is to cut-out the last element, which by construction will be the empty string '' and we don't want it
l = [ [ bin(int(s, 16))[2:] for s in l[i]] for i in range(len(l)) ]
# now the elements of these sublists are 16-bit strings such as "1111111111111111"
def mergelists(listOfLists):
l = []
for x in listOfLists:
l += x
return l
l = mergelists(l)
l = [i.zfill(16) for i in l]
def rev(s):
x = ""
for i in range(len(s)):
x += s[-1-i]
return x
n = ceil(WIDTH/16)
m = 16*n - WIDTH
assert len(l) == n*HEIGHT, "I believe this should always be true, else I've messed up somewhere; or maybe this isn't an X10 Format?"
def __aux_funct(l, n, i):
s = ""
for j in range(n):
s += rev(l[n*i + j])
return s
l = [ __aux_funct(l, n, i) for i in range(HEIGHT) ]
l = [line[:-m] for line in l]
##for line in l:
## print(line)
# seems to work just fine ^_^
f = open(saveFileName + ".binaryimage", "a")
BLACK_BOX = '#'
for line in l:
# print(len(line)) ## they all seem to be the same width
print("") # newline
f.write(line + "\n")
for bit in line:
print(BLACK_BOX, end='') if bit == "1" else print(" ", end='')
print("")
f.write("\n\n")
f.close()
# Beautiful <3

Smoothing Mask using healpy

I am using healpy.sphtfunc.smoothing for apodization of my binary mask and I am having problem that, if I have temperature cut of 100K and I made a binary mask corresponding to cut, then after apodization of mask using above routine when I apply it on my map I get 120K or number more than 100K. So I am confuse that does one do apodization on Binary mask or (map*Binary_mask)
def getMapValue(map, ra, dec, theta):
nSide = hp.pixelfunc.npix2nside(map.size)
# Extract the region around the source
vec = hp.pixelfunc.ang2vec(np.pi / 2 - np.deg2rad(dec), np.deg2rad(ra))
vec = np.array(vec)
innerPixels = hp.query_disc(nSide, vec, radius=np.radians(theta))
return innerPixels
def masking_map(map1, nside, npix, limit):
mask = np.ones(hp.nside2npix(nside), dtype=np.float64)
index = (map1 > limit)
mask[index] = 0.0
for ipix in xrange(0, npix):
theta1, phi = hp.pixelfunc.pix2ang(nside, ipix)
if 70. < np.degrees(theta1) < 110.:
mask[ipix] = 0.0
inner_pix = getMapValue(map1,329.6, 17.5, 54.0)
outer_pix = getMapValue(map1,329.6, 17.5, 62.0)
index = np.setdiff1d(outer_pix, inner_pix)
index1 = []
for ipix1 in index:
theta, phi = hp.pixelfunc.pix2ang(nside, ipix1)
if np.degrees(theta) < 90.0:
if 0.0 < np.degrees(phi)< 60.0:
index1.append(ipix1)
if 320.0 < np.degrees(phi)< 360.0:
index1.append(ipix1)
index1=np.asarray(index1)
mask[index1]=0.0
return mask
def apodiz(mask, theta):
apodiz_mask = hp.sphtfunc.smoothing(mask, fwhm=np.radians(theta),
iter=3, use_weights=True,
verbose=False)
index = (apodiz_mask < 0.0)
apodiz_mask[index] = 0.000
return apodiz_mask
def main():
filename = 'haslam408_dsds_Remazeilles2014.fits'
NSIDE = 512
input_map = loadMap(fname)
NPIX = hp.pixelfunc.nside2npix(NSIDE)
LIMIT = 50 # for 50K cut
theta_ap = 5.0 # FWHM for Apodization in degrees
Binary_mask = masking_map(input_map, NSIDE, NPIX, LIMIT)
imp_map = apodiz(Binary_mask, theta_ap)
masked_map = input_map*imp_map
hp.mollview(apoMask, xsize=2000, coord=['G'], unit=r'$T_{B}(K)$', nest=False, title='%s' % key[count])
hp.mollview(imp_map, xsize=2000, coord=['G'], unit=r'$T_{B}(K)$', nest=False, title='%s' % key[count])
hp.mollview(masked_map, xsize=2000, coord=['G'], unit=r'$T_{B}(K)$', nest=False, title='408 MHz,%s' % key[count])
hp.mollview(input_map*Binary_mask, xsize=2000, coord=['G'], unit=r'$T_{B}(K)$', nest=False, title='408 MHz,%s' % key[count])
count+=1
if __name__ == "__main__":
This is resulting map without apodization of binar mask
This is resulting map after 5 degree apodized of Binary mask

Resources