建模和显示纽约地图:病毒模拟

时间:2017-04-06 19:49:43

标签: python matplotlib

所以我写完了代码来显示纽约地图的图像,看起来应该是这样的

enter image description here

但是使用我现有的代码:

import random
import string
import math
from matplotlib import pyplot as plt

def normpdf(x, mean, sd):
"""
Return the value of the normal distribution 
with the specified mean and standard deviation (sd) at
position x.
You do not have to understand how this function works exactly. 
"""
var = float(sd)**2
denom = (2*math.pi*var)**.5
num = math.exp(-(float(x)-float(mean))**2/(2*var))
return num/denom


recovery_time = 4 # recovery time in time-steps
virality = 0.2    # probability that a neighbor cell is infected in 
              # each time step                                                  

class Cell(object):

    def __init__(self,x, y):
        self.x = x
        self.y = y 
        self.state = "S" # can be "S" (susceptible), "R" (resistant = dead), or 
                     # "I" (infected)

    def infect(self):
    pass

class Map(object):
    cells_list = []

    def __init__(self):
        self.height = 150
        self.width = 150           
        self.cells = {}

    def add_cell(self, cell):
        self.cells_list.append((cell.x, cell.y))
        self.cells_list.append(cell.state)



    def display(self):
        colors = []
        for y in range(150):
            for x in range(150):
                if (x, y) in self.cells:
                    if self.cells[(x,y)] in "S":
                        colors.append((0.0,1.0, 0.0))
                    elif self.cells[(x, y)] in "R":
                        colors.append((0.5, 0.5, 0.5))
                    else:
                        colors.append((1.0, 0.0, 0.0))
                else:
                    colors.append((0.0,0.0,0.0))
        plt.imshow(colors)

def adjacent_cells(self, x,y):
    pass


def read_map(filename):
    m = Map()
    coordinates = open(filename, 'r')
    coordinates_list = coordinates.readlines()
    for l in coordinates_list:
        line = l.strip()
        split_coords = line.split(',')
        c = Cell(split_coords[0], split_coords[1])
        m.add_cell(c)

  # ... Write this function

   return m

 read_map('nyc_map.txt').display()

我得到了这张图片:

enter image description here

顺便说一句,我们的地图是150 x 150格;创建图像我必须使用列表列表

1 个答案:

答案 0 :(得分:0)

您的代码存在很多问题:

  • 几个缩进错误
  • colors是150 * 150长度为3的元组的列表,但imshow的输入应该是一个大小为(150,150,3)的数组。
  • self.cells[(x,y)] in "S"检查字符self.cells[(x,y)]中是否包含"S"的内容,self.cells[(x,y)] == "S"只能包含self.cells{}初始化为self.cells[(x,y)],并且从未在其他位置设置,因此条件始终为false。
  • x期望yCell(split_coords[0], split_coords[1])为整数,但from matplotlib import pyplot as plt import numpy as np class Cell(object): def __init__(self,x, y): self.x = x self.y = y self.state = "S" # can be "S" (susceptible), "R" (resistant = dead), or # "I" (infected) class Map(object): def __init__(self): self.cells = {} def add_cell(self, cell): self.cells[(cell.x, cell.y)] = cell.state def display(self): colors = np.zeros((150,150,3)) for y in range(150): for x in range(150): if (x, y) in self.cells: if self.cells[(x,y)] == "S": colors[x,y,:] = (0.0,1.0, 0.0) else: colors[x, y, :] = (0.0,0.0,0.0) plt.imshow(colors) plt.show() def read_map(filename): m = Map() coordinates = open(filename, 'r') coordinates_list = coordinates.readlines() for l in coordinates_list: line = l.strip() split_coords = line.split(',') c = Cell(int(split_coords[0]), int(split_coords[1])) m.add_cell(c) # ... Write this function return m read_map('nyc_map.txt').display() 在创建单元格时会使用字符串。

以下是删除了所有代码的固定版本,例如:

var express = require('express');
        router = express.Router(),
        connect = require('connect'),
        urlParse = require('url').parse,
        fs = require('fs');
    
    var iconList = fs.readFileSync('app/data/icons.list').toString().split('\n').filter(function(site) {
        return site;
    });
    
    var random = function(max) {
        return Math.floor(Math.random() * max);
    };
    
    var icon2Site = function(icon) {
        var site = icon.replace(/_/g, '.').replace(/\.png$/, '');
        return site;
    };
    
    var breaches = [];
    
    // breaches generation
    (function() {
        for (var i = 0; i < 1000; i++) {
            var index = random(iconList.length);
            breaches.push({
                site: icon2Site(iconList[index]),
                date: Date.now() - 432000000 + random(432000000),
                number: random(100000)
            });
        }
    })();
    
    breaches.sort(function(a, b) {
        return a.date - b.date;
    });
    
    var jsonResponse = function(res, code, body) {
        res.writeHead(code, {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(body)
        });
        res.end(body);
    };
    
    var foo = connect()
        .use(connect.logger('dev'))
        .use(function(req, res, next) {
            req.parsedUrl = urlParse(req.url, true);
            next();
        })
        .use(function(req, res, next) {
            if (req.parsedUrl.pathname !== '/ws/breaches') {
                return next();
            }
            var index = parseInt(req.parsedUrl.query.index, 10) || 0;
            jsonResponse(res, 200, JSON.stringify({
                result: breaches.slice(index, index + 20)
            }));
        })
        .use(function(req, res, next) {
            if (req.parsedUrl.pathname !== '/ws/icon') {
                return next();
            }
            var site = req.parsedUrl.query.site || "";
            console.log(req.parsedUrl.query.site);
            site = site.replace(/\./g, '_') + ".png";
            jsonResponse(res, 200, JSON.stringify({
                result: "https://s3-eu-west-1.amazonaws.com/static-icons/" + site
            }));
        })
        .use(connect.static(__dirname + '/public', {
            maxAge: 1000 * 60 * 5 // Five minutes of cache
        }));
    
    
    router.get('/', function(req, res) {
        res.render('index', {pageID: 'mainData', breaches: breaches, iconList: iconList, sidebar: ['/images/vertbar.jpg'] });
        console.log(breaches);
        console.log(iconList);
    
    });
    
    module.exports = router;