def __init__(self, parent=None): super(SimWidget, self).__init__(parent) self.setupUi(self) self.colorEarth = '#009900' self.colorWater = '#27b6e9' self.timer = QTimer() self.time = 500 self.running = False fig = plt.figure() self.ax = fig.add_subplot(111) self.is_plot = False self.sim = Simulation() self.prov = load_provinces() self.countries = load_countries() #region Buttons self.worldMapBtn.clicked.connect(self.mapa_mundi) self.cubaMapBtn.clicked.connect(self.mapa_cuba) self.initialPopulationBtn.clicked.connect( self.on_initial_population_clicked) self.nextStepBtn.clicked.connect(self.on_next_step_clicked) self.simBtn.clicked.connect(self.on_sim_clicked) self.stopBtn.clicked.connect(self.on_stop_clicked) #endregion self.fill_header_table(self.tableWidget1) self.fill_header_table(self.tableWidget2)
def get_fund_related_data(request, code, dataname, freq): comp = sm.Comp(code) if freq == 'y' or freq == 'a': table = Company.objects.get(code=code).fund_y_set else: table = Company.objects.get(code=code).fund_q_set ret = {} ret['labels'] = [] ret['values'] = [] table = table.order_by('date') for t in table: date = t.date ret['labels'].append(date) v = comp.get_fund_related_data(stuff.MyDate(date), dataname, freq) if v is None: v = -1 ret['values'].append(v) return JsonResponse(ret)
import os, django, sys sys.path.append('/var/www/stockAnalyzeWeb') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stockAnalyzeWeb.settings") django.setup() from main.models import * import main.Simulation as sm from main.stuff import * from random import shuffle dfrom = MyDate('2007-12-03') dto = MyDate('2017-12-03') (sim, Sim) = sm.simInit( num=6, name='10 years buy 5 lowest PER every year', detail='Buy 5 companies with lowest PER every 365 days for 10 years', dfrom=dfrom, dto=dto) def strategy(t, comps, wallet, context): sim.progress = (dfrom.gap(t) / dfrom.gap(dto)) * 100 sim.save() if 'lastTrade' in context and context['lastTrade'] + 365 > t: return tradable = [c for c in comps if c.can_trade(t)] tradable = [ c for c in tradable
# Variables (see Documentation for description) view = True # To turn on/off the use of SAP, go to Helpers/helpers.py and change the # global variable "SAP_PHYSICS" (defined after the import statements) to True/False. seed = "r@nd0M2" robot_number = 1 maxsteps = 10000 debug = 0 # begin debugging AFTER this timestep. 0 turns off debugging, change to 1 to debug w/ PDB comment = seed # seeding the simulation: turn this on to remove randomness in brain (for debugging) # behavior between runs will be identical. random.seed(seed) # Run the Simulation, input is the random seed Sim = Simulation() Sim.start(view, robot_number) # wrapped in a try/except block to catch errors and immediately begin # pdb at exception's location try: Sim.run_simulation(view,maxsteps,debug,comment) except: _, _, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb) # Display the simulation Sim.run_visualization() #SAP 2000 templates.sdb
class SimWidget(QMainWindow, Ui_SimulationWindow): def __init__(self, parent=None): super(SimWidget, self).__init__(parent) self.setupUi(self) self.colorEarth = '#009900' self.colorWater = '#27b6e9' self.timer = QTimer() self.time = 500 self.running = False fig = plt.figure() self.ax = fig.add_subplot(111) self.is_plot = False self.sim = Simulation() self.prov = load_provinces() self.countries = load_countries() #region Buttons self.worldMapBtn.clicked.connect(self.mapa_mundi) self.cubaMapBtn.clicked.connect(self.mapa_cuba) self.initialPopulationBtn.clicked.connect( self.on_initial_population_clicked) self.nextStepBtn.clicked.connect(self.on_next_step_clicked) self.simBtn.clicked.connect(self.on_sim_clicked) self.stopBtn.clicked.connect(self.on_stop_clicked) #endregion self.fill_header_table(self.tableWidget1) self.fill_header_table(self.tableWidget2) def fill_header_table(self, table): table.setRowCount(len(name_provinces)) table.setVerticalHeaderLabels(name_provinces) table.setColumnCount(len(name_provinces)) table.setHorizontalHeaderLabels(short_provinces) def fill_table(self, table, data): for i, name in enumerate(name_provinces): d_name = data[name] for j, name in enumerate(name_provinces): value = d_name[name] item = QTableWidgetItem(str(value)) table.setItem(i, j, item) def on_stop_clicked(self): self.running = False def on_sim_clicked(self): self.running = True self.simulate() def simulate(self): if self.running: self.on_next_step_clicked() self.timer.singleShot(self.time, self.simulate) def on_initial_population_clicked(self): self.iteration = 0 self.label.setText("paso:" + str(self.iteration)) population = self.sim.population() self.iter = self.sim.simulate(10) self.mapa_cuba() self.print_population(population) # self.print_arrow() def print_arrow(self): coord_1 = self.prov["La Habana"] coord_2 = self.prov["Guantánamo"] x, y = self.m([coord_1[1], coord_2[1]], [coord_1[0], coord_2[0]]) plt.annotate("", xytext=(x[0], y[0]), xy=(x[1], y[1]), arrowprops=dict(arrowstyle='fancy')) plt.draw() def on_next_step_clicked(self): self.iteration += 1 self.label.setText("paso: " + str(self.iteration)) population, migration, living_place = next(self.iter) pp.pprint(population) self.mapa_cuba() self.print_population(population) self.fill_table(self.tableWidget1, migration) self.fill_table(self.tableWidget2, living_place) def print_population(self, population): lons = [] lats = [] labels = [] for par in population.items(): lons.append(self.prov[par[0]][1]) lats.append(self.prov[par[0]][0]) labels.append(par[1]) x, y = self.m(lons, lats) # m.plot(x, y, '#000000', markersize=10) labels = [x for x in population.values()] for label, xpt, ypt in zip(labels, x, y): plt.text(xpt, ypt, label) # plt.show() plt.draw() def mapa_mundi(self): plt.close() m = Basemap(projection='cyl', resolution='l', area_thresh=1000.0) m.drawcoastlines() m.fillcontinents(color=self.colorEarth, lake_color=self.colorWater) m.drawmapboundary(fill_color=self.colorWater) m.drawcountries() m.drawparallels(np.linspace(-90, 90, 7), labels=[1, 0, 0, 0]) m.drawmeridians(np.linspace(0, 360, 9), labels=[0, 0, 1, 0]) selected_countries = [ "Jamaica", "Cuba", "Puerto Rico", "Estados Unidos de América", "Canadá", "España", "Francia", "Venezuela", "Brasil", "Argentina" ] lons = [self.countries[x][1] for x in selected_countries] lats = [self.countries[x][0] for x in selected_countries] x, y = m(lons, lats) m.plot(x, y, 'bo', markersize=10) labels = selected_countries for label, xpt, ypt in zip(labels, x, y): plt.text(xpt - 0.3, ypt + 0.1, label, color='b') # plt.show() def mapa_cuba(self): # plt.close() self.ax.clear() c_lon, c_lat = -79.5, 21.5 delta_lon, delta_lat = 6, 2.5 self.m = Basemap(projection='cyl', resolution='i', area_thresh=0.1, lat_0=c_lat, lon_0=c_lon, llcrnrlat=c_lat - delta_lat, llcrnrlon=c_lon - delta_lon, urcrnrlat=c_lat + delta_lat, urcrnrlon=c_lon + delta_lon) self.m.drawcoastlines() self.m.fillcontinents(color=self.colorEarth, lake_color=self.colorWater) self.m.drawmapboundary(fill_color=self.colorWater) self.m.drawparallels(np.linspace(c_lat - delta_lat, c_lat + delta_lat, 7), labels=[1, 0, 0, 0], fmt='%.2f') self.m.drawmeridians(np.linspace(c_lon - delta_lon, c_lon + delta_lon, 9), labels=[0, 0, 1, 0]) lons = [x[1] for x in self.prov.values()] lats = [x[0] for x in self.prov.values()] x, y = self.m(lons, lats) self.m.plot(x, y, 'bo', markersize=6) labels = self.prov.keys() for label, xpt, ypt in zip(labels, x, y): self.ax.text(xpt - 0.3, ypt + 0.1, label, color='w') if not self.is_plot: self.is_plot = True plt.show()
def get_data(stat_func, p,n_sims=1000,k=1): s = Simulation(set_size=1, q_prob = 1e-3) stats, _,_ = s.simulation_of_statistic(stat_func, [[p,k*p]],n_sims) var = np.var(stats) E = np.mean(stats) return E, var
mode = 1 start_x = -10 stop_x = 10 periodic_boundary_conditions = True gif_name = "test" time_start = 0 # time_stop = 2*np.pi time_stop = 1 delta_t = 1e-2 gamma = np.array( [-2 for i in range(int((time_stop - time_start) / delta_t + 1))]) sim = Simulation(x_start=start_x, x_stop=stop_x, number_of_psi=number_of_psi, number_of_spatial_dimensions=number_of_spatial_dimensions, nonlinear=True) NLSE = problems.NLSE(gamma, x_start=start_x, x_stop=stop_x, number_of_psi=number_of_psi, periodic=True) init_state = NLSE.get_stationary_state() init_state = 0.7 * np.exp(-NLSE.linspace**2 / 2) u = NLSE.get_u() p = NLSE.get_P() def shooting(x0):
fill='black', text=str(person.getName()), font=("Purisa", 10)) def inoculatePeople(self): self.master.after(2000, self.subInoculate) def infectPeople(self): self.time += 1 self.infectedListA, self.infectedListB = simulate.spreadInfection() A, B = simulate.getDict() self.master.after(1000, self.subInfect) self.moveVirus(A, B) simulate = Simulation() simulate.secureStart() clusterA = simulate.populationA.getClusters() clusterB = simulate.populationB.getClusters() populationA = simulate.populationA populationB = simulate.populationB targetA = simulate.Atargetlist targetB = simulate.Btargetlist infectListA = populationA.getLevelsOfInfection() infectListB = populationB.getLevelsOfInfection() root = gwaphics.Tk() app = Application(root) ButtonThing(root, app) app.createCanvas() app.graphSign()
import os, django, sys sys.path.append('/var/www/stockAnalyzeWeb') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stockAnalyzeWeb.settings") django.setup() from main.models import * import main.Simulation as sm from main.stuff import * from random import shuffle dfrom = MyDate('2007-12-03') dto = MyDate('2017-12-03') (sim,Sim) = sm.simInit(num=5, name='10 years naive strategy', detail = 'Do naive strategy for 10 years', dfrom = dfrom, dto = dto) def strategy(t, comps, wallet, context): sim.progress = (dfrom.gap(t) / dfrom.gap(dto)) * 100 sim.save() print('\r' + str(sim.progress)+'%', end='') if 'lastTrade' in context and context['lastTrade'] + 364 > t: return tradable = [c for c in comps if c.can_trade(t)] if len(tradable) < 5:
from main.models import * import main.Simulation as sm from main.stuff import * from random import shuffle import main.crawl as cw dfrom = MyDate('2007-11-30') dto = MyDate('2018-01-26') sim = Simulation.objects.get(num=4) if sim.name == 'New strategy': sim.name = 'Price getter' sim.detail = 'Get prices' sim.save() log = sm.Logger('/var/www/stockAnalyzeWeb/main/sim_data/f4/log.txt') try: def save(comp): #earliest = comp.price_set.earliest('date').date #latest = comp.price_set.latest('date').date new_data = None for trying in range(5): try: #to = MyDate(earliest) log.writeline(comp.name) #og.writeline(str(dfrom) + '~' + str(dto)) new_data = cw.get_kospi(comp.code, start=dfrom.date, end=dto.date)
import os, django, sys sys.path.append('/var/www/stockAnalyzeWeb') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stockAnalyzeWeb.settings") django.setup() from main.models import * import main.Simulation as sm from main.stuff import * from random import shuffle dfrom = MyDate('2012-12-03') dto = MyDate('2017-12-03') (sim, Sim) = sm.simInit(num=NUM, name='New strategy', detail='New strategy created', dfrom=dfrom, dto=dto) def strategy(t, comps, wallet, context): sim.progress = (dfrom.gap(t) / dfrom.gap(dto)) * 100 sim.save() return Sim.run(strategy, startcash=1000000, modelSim=sim)
import os, django, sys sys.path.append('/var/www/stockAnalyzeWeb') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stockAnalyzeWeb.settings") django.setup() from main.models import * import main.Simulation as sm from main.stuff import * from random import shuffle dfrom = MyDate('2012-12-03') dto = MyDate('2017-12-03') (sim,Sim) = sm.simInit(num=2, name='Naive strategy for testing', detail = 'Buy 5 random companies at each rebalancing period=365', dfrom = dfrom, dto = dto) def strategy(t, comps, wallet, context): sim.progress = (dfrom.gap(t) / dfrom.gap(dto)) * 100 sim.save() print('\r' + str(sim.progress)+'%', end='') if 'lastTrade' in context and context['lastTrade'] + 364 > t: return tradable = [c for c in comps if c.can_trade(t)] if len(tradable) < 5:
# Variables (see Documentation for description) view = True # To turn on/off the use of SAP, go to Helpers/helpers.py and change the # global variable "SAP_PHYSICS" (defined after the import statements) to True/False. seed = "r@nd0M2" robot_number = 1 maxsteps = 10000 debug = 0 # begin debugging AFTER this timestep. 0 turns off debugging, change to 1 to debug w/ PDB comment = seed # seeding the simulation: turn this on to remove randomness in brain (for debugging) # behavior between runs will be identical. random.seed(seed) # Run the Simulation, input is the random seed Sim = Simulation() Sim.start(view, robot_number) # wrapped in a try/except block to catch errors and immediately begin # pdb at exception's location try: Sim.run_simulation(view, maxsteps, debug, comment) except: _, _, tb = sys.exc_info() traceback.print_exc() pdb.post_mortem(tb) # Display the simulation Sim.run_visualization() #SAP 2000 templates.sdb
from main import Simulation from visualization import Visualization # Variables view = True # Run the Simulation sim = Simulation("Papyrus") sim.start(view,1) sim.run_simulation(view,10000) # Display the simulation sim.run_visualization()
# TEMP FILE - NOT USED from main import Simulation from visualization import Visualization # Variables (see Documentation for description) view = True seed = "F@st1#lAn3-test" robot_number = 1 maxsteps = 10000 # Run the Simulation, input is the random seed sim = Simulation() sim.start(view, robot_number) sim.run_simulation(view, maxsteps) # Display the simulation sim.run_visualization()
# TEMP FILE - NOT USED from main import Simulation from visualization import Visualization # Variables (see Documentation for description) view = True seed = "F@st1#lAn3-test" robot_number = 1 maxsteps = 10000 # Run the Simulation, input is the random seed sim = Simulation() sim.start(view,robot_number) sim.run_simulation(view,maxsteps) # Display the simulation sim.run_visualization()