## python – Agent-based simulation with MESA, tornado error: I/O operation on closed file

Good day,

I am running an agent-based simulation with MESA, and psycopg2 to save intermediate information to PostgreSQL.

When I run my simulation, it successfully iterates one time, however, the second iteration does not start due to the following error:

``````ERROR:tornado.application:Uncaught exception GET /ws (127.0.0.1)
HTTPServerRequest(protocol='http', host='127.0.0.1:8521', method='GET', uri='/ws', version='HTTP/1.1', remote_ip='127.0.0.1')
Traceback (most recent call last):
File "C:UsersUser.condaenvssiminvlibsite-packagestornadowebsocket.py", line 647, in _run_callback
result = callback(*args, **kwargs)
File "C:UsersUser.condaenvssiminvlibsite-packagesmesavisualizationModularVisualization.py", line 200, in on_message
print(message)
ValueError: I/O operation on closed file.
``````

The simulation model is large, thus it is difficult to provide a reproducible example. Currently, I am stuck, because I do not have ideas of what might cause this error. At the beginning of the simulation, I create a connection to the PostgreSQL database, and I do not close it during the simulation, thus this error should be related to the MESA framework. Any guidance would be appreciated.

## C# asynchronous tasks training (turn-based simulation)

I know embarassingly little about asynchronous programming in C#, so decided to start catching up. It would help me a lot if anyone checked this basic example I’ve created.

Assumption: we’re creating a simulation where the time passes turn by turn with predefined minimal interval, e.g. 1 second. However, if any important calculations during the turn would take longer than this interval, next turn should not begin until they’re done.

I would be grateful if you could tell me if there any visible issues, code smells, or if it can be optimized. I’ve read bad things about using `Task.Run`, but I don’t really know how to tackle it better.

``````public static class Program
{
static void Main()
{
var gameTurnsController = new GameTurnsController();
var cts = new CancellationTokenSource();

try
{
// Asynchronously wait for input to send cancellation token
{
cts.Cancel();
});

gameTurnsController.PassTurns(TimeSpan.FromSeconds(1), cts.Token).Wait(cts.Token);
}
// It smells of controlling the execution flow through exception. Isn't there a better way to handle cancellation?
catch (OperationCanceledException)
{
Console.WriteLine(Environment.NewLine + "Cancelled.");
Environment.ExitCode = 0;
}

Console.WriteLine("Execution finished.");
}
}
``````
``````public class GameTurnsController
{
public async Task PassTurns(TimeSpan interval, CancellationToken cancellationToken)
{
while (true)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}

// Wait until both delay and calculation is finished
}
}

// expensive method example
{
{
long result;
// ...
// expensive math operation that returns long value
// ...
return result;
}, cancellationToken);
}
}
``````

In the above code I’ve removed most of the logs and stopwatches for clarity.

## simulation – What is the procedure for performing a binning analysis in Monte Carlo, or more generally, estimating autocorrelation times?

I’m working on a monte carlo project similar to the Ising model. I’ve found many examples on which I’ve based my code: https://github.com/danielsela42/MC_TBG_Model/blob/master/mc_project/mcproj_binned.py (my code).

From some papers I read on binning analysis, the errors after each binning step are supposed to converge. Mine ended up oscillating after some binning step. And so I’m getting negative auto correlation times.

I was hoping someone could either verify my procedure is correct, or explain a good procedure for dealing with correlated sampling.

Thank you in advance for the help!

This is my first time here. If this is not the right place to post this, where would be better?

## Simple real-time 3D wind simulation

I am a 4th-year student in the apply math department. It’s my final year, so I am working on my bachelor’s thesis. The topic is “Real-time weather effects simulation for grassland”. The huge work was done by my tutor, so the grassland simulation itself had been already implemented. Now we decided to limit the work to adding 3d wind modal and snowfall for result presentation. The snow particle system has been implemented recently, however, I’ve coped with problems while seeking information on how to implement real-time 3d wind field simulation.

There are plenty of quite complex articles on how to simplify real turbulence simulation, but it’s too excessive for my work. On the other hand, there are quite simple 2D approaches using Perlin Noise, but I can’t find something like that for the 3-dimensional scene.

Summing up, Could someone share some typical solution for my issue, or just post a good link?

Thank’s a lot in advance and sorry for my poor English.

UPD Screenshot of the scene for whatever it may be worth

## virtual machines – Can Azure run a Linux simulation?

My grandson is a senior engineering student and needs to run an AI related system simulation on a Linux based machine. Currently a pc based vm is doing this very poorly. Normal graphics should be sufficient. He estimates that the processor should be at least equivalent to an i5 (4 core).

Can this be done using Azure?

Thanks,
Steve

## table – Numerical simulation – Mathematica Stack Exchange

I want to generate a numerical simulation in table for an equational output. I have used following code. But somehow I can’t get any output. I am very novice to Mathematica. Can anyone please recommend what change I should make?

``````Subscript(r, 1) := (-2 Subscript(c, 1) + (Gamma) Subscript(c,
2) - (-2 + (Gamma)) (-a + (Tau) + (2 + (Gamma)) (((Tau) -
(Tau) Subscript((Rho), 1))/(v (Theta) Subscript((Rho), 1)))^(
1/(-1 + v))))/(-4 + (Gamma)^2)
simStep :=
Module({(Gamma), Subscript((Rho), 1),
v, (Theta), (Tau)}, {(Gamma), Subscript((Rho), 1)} =
RandomReal(1, 2);
{(Theta)} = 2;
{(Tau)} = 1;
{v} = {2};
{(Gamma)} = 0.5;
{Subscript(c, 1)} = 1;
{Subscript(c, 2)} = 1;
{Subscript((Rho), 1), Subscript(r, 1)})

$$```$$
``````

## How do I make simulation games?

I have been wanting to create simulation games but stuck in figuring out how they are built. I understand basic game development practices such as shooting, collisions, platformers, but cannot seem to find anything substantial on simulation games.
Would someone be kind enough to point me to a book/resource where I can learn how to create simulation games like:

• Rollercoaster tycoon
• Prison Architect
• Rim World
• Kairosoft games

Thank you.

## turing machines – Explain the simulation of an if else statement in LOOP

I’m learning about LOOP program and in my book I have the following command which is simulated by a LOOP program:

$$text{if} x_i = 0 text{then} text{P1} text{else} text{P2} text{end}$$

This is simulated in LOOP as:
begin{align} &x_n := 1; \ & x_{n+1} := 1; \ &text{loop} x_i text{do} x_n := x_n -1 text{end}; \ &text{loop} x_n text{do} x_{n+1} := x_{n+1} -1 text{end}; \ &text{loop} x_n text{do} text{P1} text{end}; \ &text{loop} x_{n+1} text{do} text{P2} text{end}; \ &x_n := 0; \ & x_{n+1} := 0; \ end{align}

There is no commentary for the code and I’m not sure how this even simulates the original if statement.

## c++ – Exchange simulation that trades between currencies

I need help to optimise the code as it becomes slow with a large dataset. I have an exchange simulation program that takes in market prices from a csv and then allows the user to place bids and offers for the products (currencies) that are up for trade.

OrderBookEntry.cpp contains the constructors

``````#include "OrderBookEntry.h"

OrderBookEntry::OrderBookEntry( double _price,
double _amount,
std::string _timestamp,
std::string _product,
OrderBookType _orderType,
: price(_price),
amount(_amount),
timestamp(_timestamp),
product(_product),
orderType(_orderType),
{

}

OrderBookType OrderBookEntry::stringToOrderBookType(std::string s)
{
{
}
if (s == "bid")
{
return OrderBookType::bid;
}
return OrderBookType::unknown;
}
``````

OrderBook.cpp processes bids and offers

``````#include <map>
#include <algorithm>
#include <iostream>
#include "OrderBook.h"

/** construct, reading a csv data file */
/* R1A: Retrieve the live order book from the Merklerex exchange simulation */
OrderBook::OrderBook(std::string filename)
{
}

/** return vector of all known products in the dataset*/
std::vector<std::string> OrderBook::getKnownProducts()
{
std::vector<std::string> products;

std::map<std::string,bool> prodMap;

for (OrderBookEntry& e : orders)
{
prodMap(e.product) = true;
}

// now flatten the map to a vector of strings
for (auto const& e : prodMap)
{
products.push_back(e.first);
}

return products;
}
/** return vector of Orders according to the sent filters*/
std::vector<OrderBookEntry> OrderBook::getOrders(OrderBookType type,
std::string product,
std::string timestamp)
{
std::vector<OrderBookEntry> orders_sub;
for (OrderBookEntry& e : orders)
{
if (e.orderType == type &&
e.product == product &&
e.timestamp == timestamp )
{
orders_sub.push_back(e);
}
}
return orders_sub;
}

void OrderBook::insertOrder(OrderBookEntry& order)
{
orders.push_back(order);
std::sort(orders.begin(), orders.end(), OrderBookEntry::compareByTimestamp);
}

/* R2D: Using the live order book from the exchange, decide if it should withdraw its bids at any point in time */
/* R3D: Using the live order book from the exchange, decide if it should withdraw its offers at any point in time */
void OrderBook::withdrawOrder(std::string time)
{
for (std::size_t i = orders.size() - 1; i < orders.size(); --i)
{
if(orders(i).timestamp == time && orders(i).username == "simuser")
{
orders.erase(orders.begin() + i);
}
}
}

{
product,
timestamp);
// bids = orderbook.bids
std::vector<OrderBookEntry> bids = getOrders(OrderBookType::bid,
product,
timestamp);

// sales = ()
std::vector<OrderBookEntry> sales;

// I put in a little check to ensure we have bids and asks
// to process.
if (asks.size() == 0 || bids.size() == 0)
{
return sales;
}

// sort bids highest first
std::sort(bids.begin(), bids.end(), OrderBookEntry::compareByPriceDesc);
std::cout << "max bid " << bids(0).price << std::endl;
std::cout << "min bid " << bids(bids.size()-1).price << std::endl;

{
//     for bid in bids:
for (OrderBookEntry& bid : bids)
{
//         if bid.price >= ask.price # we have a match
{
//             sale = new order()
product,

{
sale.orderType = OrderBookType::bidsale;
}
{
}

//             # now work out how much was sold and
//             # create new bids and asks covering
//             # anything that was not sold
{
//                 sales.append(sale)
sales.push_back(sale);
//                 bid.amount = 0 # make sure the bid is not processed again
bid.amount = 0;
//                 # can do no more with this ask
//                 # go onto the next ask
//                 break
break;
}
//           if bid.amount > ask.amount:  # ask is completely gone slice the bid
{
//                 sales.append(sale)
sales.push_back(sale);
//                 # we adjust the bid in place
//                 # so it can be used to process the next ask
//                 bid.amount = bid.amount - ask.amount
//                 break
break;
}

//             if bid.amount < ask.amount # bid is completely gone, slice the ask
bid.amount > 0)
{
//                 sale.amount = bid.amount
sale.amount = bid.amount;
//                 sales.append(sale)
sales.push_back(sale);
//                 # and allow further bids to process the remaining amount
//                 bid.amount = 0 # make sure the bid is not processed again
bid.amount = 0;
//                 # some ask remains so go to the next bid
//                 continue
continue;
}
}
}
}
return sales;
}
``````

functions to place bids and asks in main

``````void MerkelMain::enterAsk()
{
std::cout << "Make an ask - enter the amount: product, price, amount, eg. ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);

if (tokens.size() != 3)
{
}
else {
try {
tokens(1),
tokens(2),
currentTime,
tokens(0),
);
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
}
}
}

void MerkelMain::enterBid()
{
std::cout << "Make a bid - enter the amount: product, price, amount, eg. ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);

if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterBid Bad input! " << input << std::endl;
}
else {
try {
tokens(1),
tokens(2),
currentTime,
tokens(0),
OrderBookType::bid
);

if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterBid Bad input " << std::endl;
}
}
}
``````

``````#include <iostream>
#include <fstream>

{

}

{
std::vector<OrderBookEntry> entries;

std::ifstream csvFile{csvFilename};
std::string line;
if (csvFile.is_open())
{
while(std::getline(csvFile, line))
{
try {
OrderBookEntry obe = stringsToOBE(tokenise(line, ','));
entries.push_back(obe);
}catch(const std::exception& e)
{
}
}// end of while
}

return entries;
}

{
std::vector<std::string> tokens;
signed int start, end;
std::string token;
start = csvLine.find_first_not_of(separator, 0);
do{
end = csvLine.find_first_of(separator, start);
if (start == csvLine.length() || start == end) break;
if (end >= 0) token = csvLine.substr(start, end - start);
else token = csvLine.substr(start, csvLine.length() - start);
tokens.push_back(token);
start = end + 1;
}while(end > 0);

}

{
double price, amount;

if (tokens.size() != 5) // bad
{
std::cout << "Bad line " << std::endl;
throw std::exception{};
}
// we have 5 tokens
try {
price = std::stod(tokens(3));
amount = std::stod(tokens(4));
}catch(const std::exception& e){
throw;
}

OrderBookEntry obe{price,
amount,
tokens(0),
tokens(1),
OrderBookEntry::stringToOrderBookType(tokens(2))};

return obe;
}

std::string amountString,
std::string timestamp,
std::string product,
OrderBookType orderType)
{
double price, amount;
try {
price = std::stod(priceString);
amount = std::stod(amountString);
}catch(const std::exception& e){
throw;
}
OrderBookEntry obe{price,
amount,
timestamp,
product,
orderType};

return obe;
}
``````

Some data from the csv. 1st part is the date, 2nd part is the product, 3rd part is the OrderBookType (asks or bids), 4th part is the price and 5th part is the amount. When placing bids or asks, users do not need to enter the date but need to key in a value for everything else.

``````2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187308,7.44564869
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187307,3.467434
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187305,6.85567013
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.0218732,1.
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187163,0.03322569
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187008,0.21
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186299,0.1
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186251,0.0091
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186053,0.58
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186052,0.05
``````

## unreal 4 – Real-time fluid simulation?

I’d like to create a system in Unreal Engine 4 with glob-like fluids which interact with the environment, like the gel in Portal 2. Here’s a GIF of the gel from that: