def main(testlist, verbose=0, use_resources=None): if use_resources is None: use_resources = [] test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources if type(testlist) == type(""): testlist = [testlist] if not verbose: testlist = filter(python_check, testlist) # Psyco selective compilation is only activated here psyco.log(LOGFILE, 'a') for test in testlist: psyco.logger.write('with test ' + test, 1) psyco.full() #print "sleeping, time for a Ctrl-C !..." #import time; time.sleep(1.5) for test in testlist: for i in range(repeat_counter): print '%s, Psyco iteration %d' % (test, i+1) ok = regrtest.runtest(test, 0, verbose, 0) special_cleanup() if ok == 0: return 0 elif ok < 0: break return 1
def _activatePsyco(self): """Import Psyco if available""" try: import psyco psyco.full() if self._config["python.psyco.log"].lower() == "enabled": psyco.log(self._logDir + "/psyco.log") except ImportError: pass
def initPsyco(psycoProfile=False): try: import psyco if psycoProfile: psyco.log() psyco.profile() else: psyco.full() except ImportError: pass
def main(): if use_psyco: psyco.full() if psyco_log: psyco.log() global src import src if profile: cProfile.run("src.main()", "stats") else: src.main()
def psyco_dependency_check(): '''Try to use psyco''' print('\tPsyco availability...', end='') try: import psyco psyco.log() psyco.full() print(common.console_color('\tOK', 'green')) except ImportError: print(common.console_color("\tD'oh!", 'red')) print("No psyco module found. It's recommended to use it to improve performance\n")
def psyco_dependency_check(): '''Try to use psyco''' print '\tPsyco availability...', try: import psyco psyco.log() psyco.full() print OKGREEN + "\tOK" + ENDC except ImportError: print FAIL + "\tD'oh!" + ENDC msg = 'No psyco module found. It\'s recomended to use it to improve performance\n' print msg
def main(): use_psyco = False log = False profile = False if use_psyco: import psyco psyco.full() if log: psyco.log() global src import src.main if profile: import cProfile cProfile.run("src.main.main()","stats") else: src.main.main()
def main(): use_psyco = False log = False profile = False if use_psyco: import psyco psyco.full() if log: psyco.log() global src import src.main if profile: import cProfile cProfile.run("src.main.main()", "stats") else: src.main.main()
def main(): if options.run_shell: # Due to univlib init code having been moved into initthread, # we must duplicate (ugh!) the univlib initialization code here # in order to maintain easiness in shell operations # the code is directly copied from LobsterLoader # TODO: refactor this once i come up with a solution ### START COPY ### # init univlib ahead of time from gingerprawn.api import univlib # FIXED: not hardcoded anymore, can be changed via cmdline # default value moved there univlib.set_current_univ(_APP_OPTIONS.univ_sel) ### END OF COPY ### import code conzole = code.InteractiveConsole() conzole.interact() sys.exit(0) if not options.do_profiling: if options.run_psycoed: try: import psyco logdebug("running Psyco'd") psyco.log() psyco.profile() except ImportError: pass wxmain() else: import cProfile loginfo("running profiled, starting from here...") cProfile.run( "wxmain()", # profile result destination normpath(pathjoin(_PKG_TOPLEV, "launcher/gp-profile")), )
def startPsyco (): import leoGlobals as g try: import psyco if 0: theFile = r"c:\prog\test\psycoLog.txt" g.es("psyco now logging to:",theFile,color="blue") psyco.log(theFile) psyco.profile() psyco.full() g.es("psyco now running",color="blue") except ImportError: g.app.use_psyco = False except: print "unexpected exception importing psyco" g.es_exception() g.app.use_psyco = False
def startup_script(main_globals): """ This is the main startup script for NE1. It is intended to be run only once, and only by the code in main.py. When this function returns, the caller is intended to immediately exit normally. Parameter main_globals should be the value of globals() in __main__, which is needed in case .atom-debug-rc is executed, since it must be executed in that global namespace. """ # Note: importing all of NE1's functionality can take a long time. # To the extent possible, we want that time to be spent after # something is visible to the user, but (mostly) before the main # window is shown to the user (since showing the main window implies # that NE1 is almost ready to go). So we display a splashscreen # before doing most imports and initializations, then set up most # of our data structures and UI commands (thus importing the code # needed to implement them), and then show the main window. # (Some experimental commands are initialized after that, so that # errors that occur then can't prevent the main window from becoming # visible.) # TODO: turn the sections of code below into named functions or methods, # and perhaps split before_most_imports and before_creating_app into # more named functions or methods. The biggest split should be between # functions that need to be careful to do very few or no imports, # and functions that are free to do any imports. # Windows machines spawn and remove the shell, so no info is normally # captured. This is a first attempt to try to capture some of the console # prints that would normally be lost. The default for this code is that # it's turned off, and should remain that way until it's improved. if NE1_Build_Constants.NE1_CONSOLE_REDIRECT and os.name == "nt": capture_console = False capture_file = "" # if it's not reporting as python is the executable if not sys.executable.upper().endswith("PYTHON.EXE") and \ not sys.executable.upper().endswith("PYTHON"): try: capture_file = u"".join((sys.executable[:-4], "_console.log")) sys.stdout = open(capture_file, 'w') capture_console = True # already trapped, don't try more. except: pass if not capture_console: # Haven't captured the console log yet. Find the default user # path and try to capture there this happens if we can't write to # the normal log location, or if python.exe is the executable. tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/")) if not os.path.exists(tmpFilePath): #If it doesn't exist try: os.mkdir(tmpFilePath) #Try making one capture_console = True except: pass # we tried, but there's no easy way to capture the console if capture_console or os.path.isdir(tmpFilePath): try: # We made the directory or it already existed, try # creating the log file. capture_file = os.path.normpath(u"".join((tmpFilePath, \ "/NE1_console.log"))) sys.stdout = open(capture_file, 'w') capture_console = True except: print >> sys.__stderr__, \ "Failed to create any console log file." capture_console = False if capture_console: # Next two lines are specifically printed to the original console print >> sys.__stdout__, "The console has been redirected into:" print >> sys.__stdout__, capture_file.encode("utf_8") print print "starting NanoEngineer-1 in [%s]," % os.getcwd( ), time.asctime() print "using Python: " + sys.version try: print "on path: " + sys.executable except: pass # print the version information including official release candidate if it # is not 0 (false) if NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE: print "Version: NanoEngineer-1 v%s_RC%s" % \ (NE1_Build_Constants.NE1_RELEASE_VERSION, \ NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE) else: print "Version: NanoEngineer-1 v%s" % \ NE1_Build_Constants.NE1_RELEASE_VERSION # "Do things that should be done before most imports occur." startup_before_most_imports.before_most_imports(main_globals) from PyQt4.Qt import QApplication, QSplashScreen # "Do things that should be done before creating the application object." startup_before_most_imports.before_creating_app() ### TODO: this imports undo, env, debug, and it got moved earlier # in the startup process at some point. Those imports are probably not # too likely to pull in a lot of others, but if possible we should put up # the splash screen before doing most of them. Sometime try to figure out # how to do that. The point of this function is mostly to wrap every signal->slot # connection -- maybe it's sufficient to do that before creating the main # window rather than before creating the app? [bruce 071008 comment] # do some imports used for putting up splashscreen # (this must be done before any code that loads images from cad/src/ui) import utilities.icon_utilities as icon_utilities icon_utilities.initialize_icon_utilities() # Create the application object (an instance of QApplication). QApplication.setColorSpec(QApplication.CustomColor) #russ 080505: Make it global so it can be run under debugging below. global app app = QApplication(sys.argv) # Put up the splashscreen (if its image file can be found in cad/images). # # Note for developers: # If you don't want the splashscreen, just rename the splash image file. splash_pixmap = icon_utilities.imagename_to_pixmap("images/splash.png") # splash_pixmap will be null if the image file was not found if not splash_pixmap.isNull(): splash = QSplashScreen(splash_pixmap) # create the splashscreen splash.show() MINIMUM_SPLASH_TIME = 3.0 # I intend to add a user pref for MINIMUM_SPLASH_TIME for A7. mark 060131. splash_start = time.time() else: print "note: splash.png was not found" # connect the lastWindowClosed signal from PyQt4.Qt import SIGNAL app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit) # NOTE: At this point, it is ok to do arbitrary imports as needed, # except of experimental code. # import MWsemantics. # An old comment (I don't know if it's still true -- bruce 071008): # this might have side effects other than defining things. from ne1_ui.MWsemantics import MWsemantics # initialize modules and data structures from ne1_startup import startup_misc # do this here, not earlier, so it's free to do whatever toplevel imports it wants # [bruce 071008 change] startup_misc.call_module_init_functions() startup_misc.register_MMP_RecordParsers() # do this before reading any mmp files # create the single main window object foo = MWsemantics( ) # This does a lot of initialization (in MainWindow.__init__) import __main__ __main__.foo = foo # developers often access the main window object using __main__.foo when debugging, # so this is explicitly supported # initialize CoNTubGenerator # TODO: move this into one of the other initialization functions #Disabling the following code that initializes the ConTub plugin #(in UI it is called Heterojunction.) The Heterojunction generator or #ConTubGenerator was never ported to Qt4 platform. The plugin generator #needs a code cleanup -- ninad 2007-11-16 ##import CoNTubGenerator ##CoNTubGenerator.initialize() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *before* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_pre_main_show except NameError: pass else: func() # Do other things that should be done just before showing the main window startup_misc.pre_main_show( foo) # this sets foo's geometry, among other things foo._init_after_geometry_is_set() if not splash_pixmap.isNull(): # If the MINIMUM_SPLASH_TIME duration has not expired, sleep for a moment. while time.time() - splash_start < MINIMUM_SPLASH_TIME: time.sleep(0.1) splash.finish(foo) # Take away the splashscreen # show the main window foo.show() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *after* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_post_main_show except NameError: pass else: func() # do other things after showing the main window startup_misc.post_main_show(foo) # start psyco runtime optimizer (EXPERIMENTAL) -- # for doc see http://psyco.sourceforge.net/ # # Example: it speeds up code like this by 17 times: # (in my test, Intel Mac OS 10.4, Python 2.4.4) # x = 17 # for i in range(10**7): # x += i % 3 - 1 # # [bruce 080524] from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("Use psyco runtime optimizer (next session)?", Choice_boolean_False, prefs_key=True): # Import Psyco if available try: import psyco ## psyco.full() -- insert dna takes a lot of time, then segfaults # after printing "inside this what's this"; # plan: be more conservative about what it should optimize... # preferably bind specific functions using psyco.bind(). # For now, just tell it to only optimize the most important ones. psyco.log() # manual says: log file name looks like xxx.log-psyco # by default, where xxx is the name of the script you ran # (when I ran "python main.py" in cad/src, it wrote to main.log-psyco there) # (maybe we can pass our own pathname as an argument?) ## psyco.profile(0.2) # use profiling, optimize funcs that use # more than 20% of the time (not sure what that means exactly) # (seems safe, but from log file, i guess it doesn't do much) psyco.profile(0.05) # "aggressive" print "using psyco" pass except ImportError: print "not using psyco" pass pass # Decide whether to do profiling, and if so, with which # profiling command and into what file. Set local variables # to record the decision, which are used later when running # the Qt event loop. # If the user's .atom-debug-rc specifies PROFILE_WITH_HOTSHOT = True, # use hotshot, otherwise fall back to vanilla Python profiler. # (Note: to work, it probably has to import this module # and set this variable in this module's namespace.) try: PROFILE_WITH_HOTSHOT except NameError: PROFILE_WITH_HOTSHOT = False try: # user can set atom_debug_profile_filename to a filename in .atom-debug-rc, # to enable profiling into that file. For example: # % cd # % cat > .atom-debug-rc # atom_debug_profile_filename = '/tmp/profile-output' # ^D # ... then run NE1, and quit it # ... then in a python shell: # import pstats # p = pstats.Stats('<filename>') # p.strip_dirs().sort_stats('time').print_stats(100) # order by internal time (top 100 functions) # p.strip_dirs().sort_stats('cumulative').print_stats(100) # order by cumulative time atom_debug_profile_filename = main_globals.get( 'atom_debug_profile_filename') if atom_debug_profile_filename: print("\nUser's .atom-debug-rc requests profiling into file %r" % (atom_debug_profile_filename, )) if not type(atom_debug_profile_filename) in [ type("x"), type(u"x") ]: print "error: atom_debug_profile_filename must be a string" assert 0 # caught and ignored, turns off profiling if PROFILE_WITH_HOTSHOT: try: import hotshot except: print "error during 'import hotshot'" raise # caught and ignored, turns off profiling else: try: import cProfile as py_Profile except ImportError: print "Unable to import cProfile. Using profile module instead." py_Profile = None if py_Profile is None: try: import profile as py_Profile except: print "error during 'import profile'" raise # caught and ignored, turns off profiling except: print "exception setting up profiling (hopefully reported above); running without profiling" atom_debug_profile_filename = None # Create a fake "current exception", to help with debugging # (in case it's shown inappropriately in a later traceback). # One time this is seen is if a developer inserts a call to print_compact_traceback # when no exception is being handled (instead of the intended print_compact_stack). try: assert 0, "if you see this exception in a traceback, it is from the" \ " startup script called by main.py, not the code that printed the traceback" except: pass # Handle a mmp file passed to it via the command line. The mmp file # must be the first argument (after the program name) found on the # command line. All other arguments are currently ignored and only # one mmp file can be loaded from the command line. # old revision with --initial-file is at: svn rev 12759 # Derrick 20080520 if ((len(sys.argv) >= 2) and sys.argv[1].endswith(".mmp")): foo.fileOpen(sys.argv[1]) # Do other post-startup, pre-event-loop, non-profiled things, if any # (such as run optional startup commands for debugging). startup_misc.just_before_event_loop() if os.environ.has_key('WINGDB_ACTIVE'): # Hack to burn some Python bytecode periodically so Wing's # debugger can remain responsive while free-running # [from http://wingware.com/doc/howtos/pyqt; added by bruce 081227] # Addendum [bruce 090107]: this timer doesn't noticeably slow down NE1, # but with or without it, NE1 is about 4x slower in Wing than running # alone, at least when running test_selection_redraw.py. print "running under Wing IDE debugger; setting up timer" from PyQt4 import QtCore timer = QtCore.QTimer() def donothing(*args): x = 0 for i in range(0, 100): x += i timer.connect(timer, QtCore.SIGNAL("timeout()"), donothing) timer.start(200) # Finally, run the main Qt event loop -- # perhaps with profiling, depending on local variables set above. # This does not normally return until the user asks NE1 to exit. # Note that there are three copies of the statement which runs that loop, # two inside string literals, all of which presumably should be the same. if atom_debug_profile_filename: if PROFILE_WITH_HOTSHOT: profile = hotshot.Profile(atom_debug_profile_filename) profile.run('app.exec_()') else: py_Profile.run( 'from ne1_startup.main_startup import app; app.exec_()', atom_debug_profile_filename) print("\nProfile data was presumably saved into %r" % (atom_debug_profile_filename, )) else: # if you change this code, also change both string literals just above app.exec_() # Now return to the caller in order to do a normal immediate exit of NE1. return # from startup_script
def start_loop(self, companyName=None, companyCapital=None, loadPreviousGame=None): """ companyName string of a company that will play as current player. If none, the game will run in simulation mode companyCapital int with the starting capital of the newly started company. loadPreviousGame filename of a save game that can be loaded """ #initilizing screen stuff window_size = global_variables.window_size pygame.init() if global_variables.fullscreen: window = pygame.display.set_mode(window_size, FULLSCREEN) else: window = pygame.display.set_mode(window_size) icon = pygame.image.load(os.path.join("images", "window_icon.png")) pygame.display.set_icon(icon) pygame.mouse.set_cursor(*pygame.cursors.arrow) #initializing the world - depends on if a previous game should be loaded if loadPreviousGame is not None: self.setSol( solarsystem.solarsystem(global_variables.start_date, de_novo_initialization=False)) self.sol().load_solar_system(loadPreviousGame) else: self.setSol( solarsystem.solarsystem(global_variables.start_date, de_novo_initialization=True)) #initialize current player company if companyName is not None: if self.sol().current_player is not None: raise Exception( "The loaded solar system already had a current player") automation_dict = { "Demand bidding (initiate buying bids)": False, "Supply bidding (initiate selling bids)": False, "Asset market (buy bases and firms)": False, "Commodities market (start commodity producing firms)": False, "Tech market (buy and sell technology)": False, "Transport market (start up merchant firms)": False, "Evaluate firms (close problematic firms)": False, "Start research firms": False, "Pick research (pick research automatically)": False, "Expand area of operation (search for new home cities)": False } if companyName in self.sol().companies.keys(): self.sol().current_player = self.sol().companies[companyName] self.sol().current_player.automation_dict = automation_dict self.sol().current_player.automation_dict[ "Demand bidding (initiate buying bids)"] = True self.sol().current_player.automation_dict[ "Supply bidding (initiate selling bids)"] = True self.sol().current_player.capital = companyCapital else: model_companyName = random.choice(self.sol().companies.keys()) model_company = self.sol().companies[model_companyName] new_company = company.company(self.sol(), model_company.company_database, deviation=5, companyName=companyName, capital=companyCapital) self.sol().companies[companyName] = new_company new_company.automation_dict = automation_dict self.sol().current_player = new_company #loading planets that are often used: print "loading earth" self.sol().planets["earth"].pickle_all_projections() print "finished loading" #divide the surface in action and non-action action_rect = pygame.Rect(0, 0, global_variables.window_size[0] - 150, global_variables.window_size[1] - 100) right_side_rect = pygame.Rect(global_variables.window_size[0] - 150, 0, 150, global_variables.window_size[1]) message_rect = pygame.Rect(10, global_variables.window_size[1] - 100, global_variables.window_size[0] - 170, 100) action_surface = window.subsurface(action_rect) right_side_surface = window.subsurface(right_side_rect) message_surface = window.subsurface(message_rect) #switch to determine planetary mode or solarsystem mode from beginning mode_before_change = self.sol().display_mode if self.sol().display_mode == "solar_system": surface = self.sol().draw_solar_system( zoom_level=self.sol().solar_system_zoom, date_variable=self.sol().current_date, center_object=self.sol().current_planet.planet_name) if self.sol().display_mode == "planetary": self.sol().current_planet = self.sol().planets["earth"] surface = self.sol().current_planet.draw_entire_planet( self.sol().current_planet.eastern_inclination, self.sol().current_planet.northern_inclination, self.sol().current_planet.projection_scaling) action_surface.blit(surface, (0, 0)) pygame.display.flip() #Initialising the GUI self.setGui( gui.gui(right_side_surface, message_surface, action_surface, self.sol())) #getting psyco if available try: import psyco psyco.log() psyco.profile() except ImportError: pass i = 0 self.sol().launchThread() self.eventLoop()
# reachable is a map from population tuples to a valid word with # that population reachable = {} # start off with just the seed note_reachable(reachable, seed) for w in all_words: w_pop = make_pop(w) if reachable.has_key(w_pop): # already have an anagram of w continue # for each possible predecessor of w, see if it is already reachable for v_pop in make_reduced(w_pop): if reachable.has_key(v_pop): print "%s reachable from %s" % (w, reachable[v_pop]) note_reachable(reachable, w) break if __name__ == '__main__': try: # Cool! Psyco roughly halves the runtime. import psyco psyco.log('/tmp/psyco.log') psyco.full() except: print 'Psyco not found, ignoring it' main()
def __init__(self, content, logger, key_set): ##============================================================================ self.version = '0.0.1a' self.objects = [] self.logger = logger self.logger.log.info('Init Game and Game Screen.') self.debug_level = 'debug' # prints errors verbosely to the game screen # On release, just a confirmation menu # Also affects the use of the python interpreter # in the console, disabled on release '''try: self.logger.log.debug('Init gEngine...') import cEngine as gEngine # Try importing the pyd self.logger.log.debug('gEngine pyd/so imported') except ImportError, err: # if that fails, import the python prototype sys.path.append(os.path.join(sys.path[0], 'gEngine')) self.logger.log.debug('gEngine pyd/so import failed, using python prototype') self.logger.log.exception(err) import gEngine.gEngine as gEngine''' import gEngine.gEngine as gEngine try: self.logger.log.debug("Importing Psyco.") import psyco psyco.full() psyco.log() psyco.profile() self.logger.log.debug('Psyco full used.') except ImportError: self.logger.log.debug("Importing Psyco failed.") pass #libtcod.console_set_keyboard_repeat(250,250) self.gEngine = gEngine.gEngine(SCREEN_WIDTH, SCREEN_HEIGHT, 'Ascension 0.0.1a', False, LIMIT_FPS) try: font = os.path.join(sys.path[0], 'terminal10x10_gs_tc.png') self.gEngine.console_set_custom_font(font, libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE) except: pass self.gEngine.init_root() self.con = self.gEngine.console_new(MAP_WIDTH, MAP_HEIGHT) self.panel = self.gEngine.console_new(SCREEN_WIDTH, PANEL_HEIGHT) self.toolbar = self.gEngine.console_new(SCREEN_WIDTH, 5) x = 32/2 x = SCREEN_WIDTH/2 - x self.hotbar = HotBar(x, 0, self.gEngine, self.toolbar) z=1 index = ord('1') for i in range(10): if index == ord(':'): index = ord('0') s = HotBarSlot(None, z+x, PANEL_Y-4, z, chr(index), self.gEngine) self.hotbar.add_slot(s) z += 3 index += 1 self.message = Message(self.panel, MSG_HEIGHT, MSG_WIDTH, MSG_X, self.logger, self.debug_level) self.build_objects = GameObjects(content) self.ticker = Ticker() self.Map = map.Map(MAP_HEIGHT, MAP_WIDTH, ROOM_MIN_SIZE, ROOM_MAX_SIZE, MAX_ROOMS, MAX_ROOM_MONSTERS, MAX_ROOM_ITEMS, self.logger) self.keys = key_set self.setup_keys() self.current_dungeon = [] # an array that holds all off the dungeon levels #self.console = console.Console(self, SCREEN_WIDTH-2, SCREEN_HEIGHT/2, self.debug_level) self.depth = None self.game_state = None self.dev_mode = dev_mode.DevMode(self.gEngine, self.Map) #libtcod.console_set_keyboard_repeat(50, 50) libtcod.sys_set_renderer(libtcod.RENDERER_GLSL)
def startup_script( main_globals): """ This is the main startup script for NE1. It is intended to be run only once, and only by the code in main.py. When this function returns, the caller is intended to immediately exit normally. Parameter main_globals should be the value of globals() in __main__, which is needed in case .atom-debug-rc is executed, since it must be executed in that global namespace. """ # Note: importing all of NE1's functionality can take a long time. # To the extent possible, we want that time to be spent after # something is visible to the user, but (mostly) before the main # window is shown to the user (since showing the main window implies # that NE1 is almost ready to go). So we display a splashscreen # before doing most imports and initializations, then set up most # of our data structures and UI commands (thus importing the code # needed to implement them), and then show the main window. # (Some experimental commands are initialized after that, so that # errors that occur then can't prevent the main window from becoming # visible.) # TODO: turn the sections of code below into named functions or methods, # and perhaps split before_most_imports and before_creating_app into # more named functions or methods. The biggest split should be between # functions that need to be careful to do very few or no imports, # and functions that are free to do any imports. # print the version information including official release candidate if it # is not 0 (false) if NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE: print "Version: NanoEngineer-1 v%s_RC%s" % \ (NE1_Build_Constants.NE1_RELEASE_VERSION, \ NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE) else: print "Version: NanoEngineer-1 v%s" % \ NE1_Build_Constants.NE1_RELEASE_VERSION # "Do things that should be done before most imports occur." startup_before_most_imports.before_most_imports( main_globals ) from PyQt4.Qt import QApplication, QSplashScreen # "Do things that should be done before creating the application object." startup_before_most_imports.before_creating_app() ### TODO: this imports undo, env, debug, and it got moved earlier # in the startup process at some point. Those imports are probably not # too likely to pull in a lot of others, but if possible we should put up # the splash screen before doing most of them. Sometime try to figure out # how to do that. The point of this function is mostly to wrap every signal->slot # connection -- maybe it's sufficient to do that before creating the main # window rather than before creating the app? [bruce 071008 comment] # Create the application object (an instance of QApplication). QApplication.setColorSpec(QApplication.CustomColor) #russ 080505: Make it global so it can be run under debugging below. global app app = QApplication(sys.argv) # do some imports used for putting up splashscreen import utilities.icon_utilities as icon_utilities icon_utilities.initialize() # Put up the splashscreen (if its image file can be found in cad/images). # # Note for developers: # If you don't want the splashscreen, just rename the splash image file. splash_pixmap = icon_utilities.imagename_to_pixmap( "images/splash.png" ) # splash_pixmap will be null if the image file was not found if not splash_pixmap.isNull(): splash = QSplashScreen(splash_pixmap) # create the splashscreen splash.show() MINIMUM_SPLASH_TIME = 3.0 # I intend to add a user pref for MINIMUM_SPLASH_TIME for A7. mark 060131. splash_start = time.time() else: print "note: splash.png was not found" # connect the lastWindowClosed signal from PyQt4.Qt import SIGNAL app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit) # NOTE: At this point, it is ok to do arbitrary imports as needed, # except of experimental code. # import MWsemantics. # An old comment (I don't know if it's still true -- bruce 071008): # this might have side effects other than defining things. from ne1_ui.MWsemantics import MWsemantics # initialize modules and data structures from ne1_startup import startup_misc # do this here, not earlier, so it's free to do whatever toplevel imports it wants # [bruce 071008 change] startup_misc.call_module_init_functions() startup_misc.register_MMP_RecordParsers() # do this before reading any mmp files # create the single main window object foo = MWsemantics() # This does a lot of initialization (in MainWindow.__init__) import __main__ __main__.foo = foo # developers often access the main window object using __main__.foo when debugging, # so this is explicitly supported # initialize CoNTubGenerator # TODO: move this into one of the other initialization functions #Disabling the following code that initializes the ConTub plugin #(in UI it is called Heterojunction.) The Heterojunction generator or #ConTubGenerator was never ported to Qt4 platform. The plugin generator #needs a code cleanup -- ninad 2007-11-16 ##import CoNTubGenerator ##CoNTubGenerator.initialize() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *before* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_pre_main_show except NameError: pass else: func() # Do other things that should be done just before showing the main window startup_misc.pre_main_show(foo) # this sets foo's geometry, among other things foo._init_after_geometry_is_set() if not splash_pixmap.isNull(): # If the MINIMUM_SPLASH_TIME duration has not expired, sleep for a moment. while time.time() - splash_start < MINIMUM_SPLASH_TIME: time.sleep(0.1) splash.finish( foo ) # Take away the splashscreen # show the main window foo.show() # set up the sponsors system and perhaps show the permission dialog if sys.platform != 'darwin': #bruce 070515 added condition to disable this on Mac, until Brian fixes the hang on Mac. # Note: this is enabled in the Mac released version, due to a patch during the release # building process, at least in A9.1. from sponsors.Sponsors import PermissionDialog ## print "start sponsors startup code" # Show the dialog that asks permission to download the sponsor logos, then # launch it as a thread to download and process the logos. # permdialog = PermissionDialog(foo) if permdialog.needToAsk: permdialog.exec_() permdialog.start() ## print "end sponsors startup code" # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *after* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_post_main_show except NameError: pass else: func() # do other things after showing the main window startup_misc.post_main_show(foo) # start psyco runtime optimizer (EXPERIMENTAL) -- # for doc see http://psyco.sourceforge.net/ # # Example: it speeds up code like this by 17 times: # (in my test, Intel Mac OS 10.4, Python 2.4.4) # x = 17 # for i in range(10**7): # x += i % 3 - 1 # # [bruce 080524] from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("Use psyco runtime optimizer (next session)?", Choice_boolean_False, prefs_key = True ): # Import Psyco if available try: import psyco ## psyco.full() -- insert dna takes a lot of time, then segfaults # after printing "inside this what's this"; # plan: be more conservative about what it should optimize... # preferably bind specific functions using psyco.bind(). # For now, just tell it to only optimize the most important ones. psyco.log() # manual says: log file name looks like xxx.log-psyco # by default, where xxx is the name of the script you ran # (when I ran "python main.py" in cad/src, it wrote to main.log-psyco there) # (maybe we can pass our own pathname as an argument?) ## psyco.profile(0.2) # use profiling, optimize funcs that use # more than 20% of the time (not sure what that means exactly) # (seems safe, but from log file, i guess it doesn't do much) psyco.profile(0.05) # "aggressive" print "using psyco" pass except ImportError: print "not using psyco" pass pass # Decide whether to do profiling, and if so, with which # profiling command and into what file. Set local variables # to record the decision, which are used later when running # the Qt event loop. # If the user's .atom-debug-rc specifies PROFILE_WITH_HOTSHOT = True, use hotshot, otherwise # fall back to vanilla Python profiler. try: PROFILE_WITH_HOTSHOT except NameError: PROFILE_WITH_HOTSHOT = False try: # user can set this to a filename in .atom-debug-rc, # to enable profiling into that file atom_debug_profile_filename = main_globals['atom_debug_profile_filename'] if atom_debug_profile_filename: print ("\nUser's .atom-debug-rc requests profiling into file %r" % (atom_debug_profile_filename,)) if not type(atom_debug_profile_filename) in [type("x"), type(u"x")]: print ("error: atom_debug_profile_filename must be a string;" + "running without profiling") assert 0 # caught and ignored, turns off profiling if PROFILE_WITH_HOTSHOT: try: import hotshot except: print "error during 'import hotshot'; running without profiling" raise # caught and ignored, turns off profiling else: try: import cProfile except: print "error during 'import profile'; running without profiling" raise # caught and ignored, turns off profiling except: atom_debug_profile_filename = None # Create a fake "current exception", to help with debugging # (in case it's shown inappropriately in a later traceback). # One time this is seen is if a developer inserts a call to print_compact_traceback # when no exception is being handled (instead of the intended print_compact_stack). try: assert 0, "if you see this exception in a traceback, it is from the" \ " startup script called by main.py, not the code that printed the traceback" except: pass # Handle a mmp file passed to it via the command line. The mmp file # must be the first argument (after the program name) found on the # command line. All other arguments are currently ignored and only # one mmp file can be loaded from the command line. # old revision with --initial-file is at: svn rev 12759 # Derrick 20080520 if ((len(sys.argv) >= 2) and sys.argv[1].endswith(".mmp")): foo.fileOpen(sys.argv[1]) # Finally, run the main Qt event loop -- # perhaps with profiling, depending on local variables set above. # This does not normally return until the user asks NE1 to exit. # Note that there are three copies of the statement which runs that loop, # two inside string literals, all of which presumably should be the same. if atom_debug_profile_filename: if PROFILE_WITH_HOTSHOT: profile = hotshot.Profile(atom_debug_profile_filename) profile.run('app.exec_()') else: cProfile.run('from ne1_startup.main_startup import app; app.exec_()', atom_debug_profile_filename) print ("\nProfile data was presumably saved into %r" % (atom_debug_profile_filename,)) else: # if you change this code, also change the string literals just above app.exec_() # Now return to the caller in order to do a normal immediate exit of NE1. return # from startup_script
import time import psyco psyco.log('log.txt') psyco.full() def brickEdges(form,n): li = [0 for i in xrange(n)] index=-1 for i in form: if i=='2':index+=2 else:index+=3 li[index]=1 li.pop() return li def canComeAfter(a,b,n): can = True l2=brickEdges(b,n) l1=brickEdges(b,n) for i,j in zip(l1,l2): if i==j and i==1:can=False return can def importPossibleRows(w,h): def permutate(n,threes): a=[0 for i in xrange(n)] li=[] while a!=[1]*n: f = [] for i in a: if i==1: f.append('2') else:
def main(): import optparse usage = "%prog [options] command input-file-patterns" oparser = optparse.OptionParser(usage) oparser.add_option( "-l", "--logfilename", default="", help="contains error messages") oparser.add_option( "-v", "--verbosity", type="int", default=0, help="level of information and diagnostics provided") oparser.add_option( "-p", "--pickleable", type="int", default=1, help="1: ensure Book object is pickleable (default); 0: don't bother") oparser.add_option( "-m", "--mmap", type="int", default=-1, help="1: use mmap; 0: don't use mmap; -1: accept heuristic") options, args = oparser.parse_args() if len(args) != 2: oparser.error("Expected 2 args, found %d" % len(args)) if PSYCO: try: import psyco psyco.log() psyco.profile() except ImportError: pass cmd = args[0] xlrd_version = getattr(xlrd, "__VERSION__", "unknown; before 0.5") if cmd == 'dump': xlrd.dump(args[1]) sys.exit(0) if cmd == 'version': print "xlrd version:", xlrd_version sys.exit(0) if options.logfilename: logfile = open(options.logfilename, 'w') else: logfile = sys.stdout mmap_opt = options.mmap mmap_arg = xlrd.USE_MMAP if mmap_opt in (1, 0): mmap_arg = mmap_opt elif mmap_opt != -1: print 'Unexpected value (%r) for mmap option -- assuming default' % mmap_opt for pattern in args[1:]: for fname in glob.glob(pattern): print >> logfile, "\n=== File: %s ===" % fname try: t0 = time.time() bk = xlrd.open_workbook(fname, verbosity=options.verbosity, logfile=logfile, pickleable=options.pickleable, use_mmap=mmap_arg) t1 = time.time() print >> logfile, "Open took %.2f seconds" % (t1-t0,) except xlrd.XLRDError: print >> logfile, "*** Open failed: %s: %s" % sys.exc_info()[:2] continue except: print >> logfile, "*** Open failed: %s: %s" % sys.exc_info()[:2] continue t0 = time.time() if cmd == 'ov': # OverView show(bk, 0) elif cmd == 'show': # all rows show(bk) elif cmd == '2rows': # first row and last row show(bk, 2) elif cmd == '3rows': # first row, 2nd row and last row show(bk, 3) elif cmd == 'bench': show(bk, printit=False) else: print >> logfile, "*** Unknown command <%s>" % cmd sys.exit(1) t1 = time.time() print >> logfile, "\ncommand took %.2f seconds\n" % (t1-t0,)
def run(fileName=None, *args, **keywords): """Initialize and run Leo""" if not isValidPython(): return # Import leoGlobals, but do NOT set g. import leoGlobals # Create the application object. import leoApp leoGlobals.app = leoApp.LeoApp() g = leoGlobals assert (g.app) # NOW we can set g. g.app.loadDir = computeLoadDir( ) # Depends on g.app.tkEncoding: uses utf-8 for now. import leoConfig g.app.config = leoConfig.config() g.app.setEncoding() # 10/20/03: do this earlier script = getBatchScript() if script: createNullGuiWithScript(script) fileName = None else: #@ << print encoding info >> #@+node:orkman.20050213172746.3:<< print encoding info >> g.es("leoConfig.txt encoding: " + g.app.config.config_encoding, color="blue") if 0: # This is just confusing for users. g.es("Text encoding: " + g.app.tkEncoding, color="blue") #@nonl #@-node:orkman.20050213172746.3:<< print encoding info >> #@nl # Load plugins. Plugins may create g.app.gui. g.doHook("start1") if g.app.killed: return # Support for g.app.forceShutdown. # Create the default gui if needed. #if g.app.gui == "swing" : # g.app.createSwingGui() if g.app.gui == None: #g.app.createTkGui() g.app.createSwingGui() if g.app.use_gnx: if not g.app.leoID: g.app.setLeoID() # Forces the user to set g.app.leoID. import leoNodes g.app.nodeIndices = leoNodes.nodeIndices() # Initialize tracing and statistics. g.init_sherlock(args) g.clear_stats() #@ << start psycho >> #@+node:orkman.20050213172746.4:<< start psycho >> if g.app.config.use_psyco: try: import psyco if 0: file = r"c:\prog\test\psycoLog.txt" g.es("psyco now logging to", file, color="blue") psyco.log(file) psyco.profile() psyco.full() g.es("psyco now running", color="blue") except ImportError: pass except: print "unexpected exception importing psyco" g.es_exception() #@nonl #@-node:orkman.20050213172746.4:<< start psycho >> #@nl # Create the main frame. Show it and all queued messages. c, frame = createFrame(fileName) if not frame: return if g.app.disableSave: g.es("disabling save commands", color="red") g.app.writeWaitingLog() v = c.currentVnode() #g.doHook("start2",c=c,v=v,fileName=fileName) g.enableIdleTimeHook() frame.tree.redraw() frame.body.setFocus() g.app.initing = False # "idle" hooks may now call g.app.forceShutdown. g.app.gui.runMainLoop()
def main(): #why do only these need to be reminded they are global? global simulationFile global theWorldSize global startPopulationSize global seedPlacement global sList #Import Psyco if possible try: import psyco psyco.log() psyco.full() except ImportError: pass CFDGtext="" #################################### ###experiments in importing events import yaml if os.path.exists(eventFile): print "***Loading event file: %s***" % (eventFile) theFile=open(eventFile) eventData=yaml.load(theFile) theFile.close eventTimes=eventData.keys() else: eventTimes=[] ##################################### if debug==1: print "***debug is on***" theGarden= worldBasics.garden() theGarden.platonicSeeds={} theGarden.theRegions=[] #### #########Check for multiple species. If none, use default fileList=os.listdir("Species") ymlList=[] pythonList=[] useDefaultYml=True print "***Checking for species...***" for file in fileList: theExtension=os.path.splitext(file)[1] if theExtension==".yml": #add this file to the list of yaml files ymlList.append(file) useDefaultYml=False elif theExtension==".py": #this might be override info for a species #add this file to the list of species python files #this isn't implemented pythonList.append(file) fileList=[] ########## if resumeSim==1 and not simulationFile=="": simulationFile=open(simulationFile, 'r') theGarden=pickle.load(simulationFile) simulationFile.close() theWorldSize=theGarden.theWorldSize print "***Resuming Simulation: %s as %s***" % (theGarden.name, simulationName) theGarden.name=simulationName startPopulationSize=theGarden.numbPlants ##this should reload species data. ###Important if you want to compare runs if reloadSpeciesData==1: ###fileLoc will be different for each species eventually fileLoc="SERA_Data/Default_species.txt" for item in theGarden.soil: item.importPrefs(fileLoc) else: theGarden.makePlatonicSeedDict(ymlList, Species1) print "***Species loaded.***" theGarden.name=simulationName theGarden.theWorldSize=theWorldSize print "***Beginning Simulation: %s***" % (simulationName) theGarden.showProgressBar=showProgressBar print " World size: %ix%i" % (theWorldSize, theWorldSize) print " Maximum population size will be: %i" % (maxPopulation) print " and" print " Running simulation for %i cycles" % (maxCycles) print " (whichever comes first)" print " Starting population size: %i" % (startPopulationSize) if theGarden.carbonAllocationMethod==0: print " Plants will allocate carbon to stem and leaf using methods defined by the species." else: print " All plants will allocate carbon to stem and leaf using method %i" % (theGarden.carbonAllocationMethod) print "" if produceGraphics==1: print " Graphical output will be produced." if theView==1: print " Graphical output will be a bottom-up view." elif theView==2: print " Graphical output will be a top-down view." elif theView==3: print " Graphical output will be a side-view." elif theView==12: print " Graphical output will be a combination bottom-up and top-down view." elif theView==21: print " Graphical output will be a combination top-down and bottom-up view." elif theView==23: print " Graphical output will be a combined top-down and side view." elif theView==13: print " Graphical output will be a combined bottom-up and side view." elif theView==123: print " Graphical output will be a combination bottom-up, top-down and side view." if produceVideo==1: print " Graphical output will include a %s frame/second video." % (framesPerSecond) ###I think this is where to start the times to repeat bit for x in range(timesToRepeat): ###make necessary directories outputDirectory="Output-"+simulationName+"/" outputDirectory=makeDirectory(outputDirectory) if produceGraphics==1 or produceDXFGraphics==1: outputGraphicsDirectory = outputDirectory +"Graphics/" makeDirectory(outputGraphicsDirectory) if produceDXFGraphics==1: outputDXFGraphicsDirectory = outputGraphicsDirectory +"DXF/" makeDirectory(outputDXFGraphicsDirectory) ####SUPER IMPORTANT!!!! ####DON'T USE SPACES IN DIR NAMES! ####COMMAND LINES HATE THAT SHIT if theView==1: outputGraphicsDirectory = outputGraphicsDirectory +"bottom-up/" makeDirectory(outputGraphicsDirectory) elif theView==2: outputGraphicsDirectory = outputGraphicsDirectory +"top-down/" makeDirectory(outputGraphicsDirectory) elif theView==3: outputGraphicsDirectory = outputGraphicsDirectory +"side/" makeDirectory(outputGraphicsDirectory) elif theView==12: outputGraphicsDirectory = outputGraphicsDirectory +"combined-bottom-top/" makeDirectory(outputGraphicsDirectory) elif theView==21: outputGraphicsDirectory = outputGraphicsDirectory +"combined-top-bottom/" makeDirectory(outputGraphicsDirectory) elif theView==13: outputGraphicsDirectory = outputGraphicsDirectory +"combined-bottom-side/" makeDirectory(outputGraphicsDirectory) elif theView==23: outputGraphicsDirectory = outputGraphicsDirectory +"combined-top-side/" makeDirectory(outputGraphicsDirectory) elif theView==123: outputGraphicsDirectory = outputGraphicsDirectory +"combined-bottom-top-side/" makeDirectory(outputGraphicsDirectory) if not archive=="n": saveDirectory = outputDirectory+"Save_points/" makeDirectory(saveDirectory) if not saveData=="n": dataDirectory = outputDirectory+"Simulation_data/" makeDirectory(dataDirectory) makeDirectory(dataDirectory+"Seeds/") makeDirectory(dataDirectory+"Plants/") makeDirectory(dataDirectory+"Corpses/") if resumeSim==0: #2008.11.06 Moved a huge block of code related to placing seeds to vworldr.py theGarden.placeSeed(seedPlacement, sList, startPopulationSize, useDefaultYml, ymlList) if produceGraphics and CFDGtext=="": CFDGtext=outputGraphics.initCFDGText(theGarden, theView, percentTimeStamp, 50.0) ####### cycleNumber=0 print "\n***Running simulation.***" if not showProgressBar and not runningInNodeBox: theProgressBar= progressBarClass.progressbarClass(maxCycles,"*") #why -1? because index 0. So if total=100, 0-99. #print "Cycle, plant age, Mass Stem, Mass Leaf, # Seeds, Mass all Seeds, Radius Stem, Radius Leaf, Height Plant, areaPhoto, new mass" while (theGarden.numbPlants<=maxPopulation and cycleNumber<=maxCycles) and (theGarden.numbPlants+theGarden.numbSeeds)>0: ################################################################################### ####Experimental scripting event stuff # if cycleNumber in eventTimes: # for aItem in eventData[cycleNumber]: # for aKey in aItem.keys(): # if aKey=="Garden": # if debug==1: print "debug: A garden related event has been triggered." # theDict=aItem[aKey][0] # gardenAttrs=theDict.keys() # for theGardenAttr in gardenAttrs: # setattr(theGarden, theGardenAttr, theDict[theGardenAttr]) # gardenAttrs="" elif aKey=="Killzone" or aKey=="Safezone": if debug==1: print "debug: generation of a zone event has been triggered." theDict=aItem[aKey][0] # zoneAttrs=theDict.keys() zoneX=float(theDict['x']) zoneY=float(theDict['y']) zoneSize=float(theDict['size']) zoneShape=theDict['shape'] if zoneShape not in ['circle','square']: print "***WARNING: improper zone shape defined. Defaulting to square.***" zoneShape='square' zoneTarget=theDict['target'] if zoneTarget not in ['all','plants','seeds']: print "***WARNING: improper zone target defined. Defaulting to all.***" zoneTarget='all' if zoneShape=='circle': killThese=[] for theObject in theGarden.soil: if theObject.isSeed: r=theObject.radiusSeed else: r=theObject.radiusStem theResult=geometry_utils.checkOverlap(theObject.x, theObject.y, r, zoneX, zoneY, zoneSize) if theResult>0 and aKey=='Killzone': if zoneTarget=='all' or (theObject.isSeed and zoneTarget=='seeds') or (not theObject.isSeed and zoneTarget=='plants'): killThese.append(theObject) elif aKey=='Safezone': if theResult==0: killThese.append(theObject) elif theResult>0: if (theObject.isSeed and zoneTarget=='plants') or (not theObject.isSeed and zoneTarget=='seeds'): killThese.append(theObject) for theObject in killThese: theObject.causeOfDeath="zone" theGarden.kill(theObject) elif aKey=="Seed": if debug==1: print "debug: A seeding related event has been triggered." # theDict=aItem[aKey][0] # seedingInfo=theDict.keys() # for infoItem in seedingInfo: if infoItem=="number" and not seedPlacement=="fromFile": startPopulationSize=theDict[infoItem] if infoItem=="species": sList=theDict[infoItem] if sList=="random": sList=[] if infoItem=="placement": seedPlacement=theDict[infoItem] if seedPlacement=="hexagon": seedPlacement="hex" #just make sure it is consistant if os.path.isfile(seedPlacement): theFile=open(seedPlacement) try: sList=theFile.readlines() finally: theFile.close() sList=checkSeedPlacementList(sList) startPopulationSize=len(sList) seedPlacement="fromFile" if not seedPlacement=="fromFile" and not sList==[]: newList=[] for j in range(startPopulationSize): newList.append(sList) #print sList sList=newList newList=[] #print sList theGarden.placeSeed(seedPlacement, sList, startPopulationSize, useDefaultYml, ymlList) elif aKey=="Region": if debug: print "debug: Region event detected..." theDict=aItem[aKey][0] regionAttrs=theDict.keys() theRegionName=str(theDict['name']) if debug: print "debug: Region %s event detected." % (theRegionName) regionNames=[] for i in theGarden.theRegions: regionNames.append(i.name) if theRegionName in regionNames: for j in theGarden.theRegions: if j.name==theRegionName: theRegion=j break for aAttr in regionAttrs: if not getattr(theRegion,aAttr,"does not exist")==theDict[aAttr]: if debug: print "debug: Region %s has had a change in one or more attributes." % (theRegionName) updatePlants=True break #if (not theRegion.size==theDict["size"]) or (not theRegion.x==theDict["x"]) or (not theRegion.y==theDict["y"]) or (not theRegion.shape==theDict["shape"]): # if debug:print "debug: a region has changed shape, size or location" # updatePlants=True ##now just read in the values# if debug: print "debug: Updating attributes for region %s." % (theRegionName) for theRegionAttr in regionAttrs: # setattr(theRegion, theRegionAttr, theDict[theRegionAttr]) # if updatePlants: if debug:print "debug: updating plants with changed region info" for aPlant in theGarden.soil: plantX=aPlant.x plantY=aPlant.y if theRegion.shape=='square': inSubregion=geometry_utils.pointInsideSquare(theRegion.x, theRegion.y, theRegion.size, plantX, plantY) elif theRegion.shape=='circle': #size needs to be radius but region defines diameter inSubregion=geometry_utils.pointInsideCircle(theRegion.x, theRegion.y, theRegion.size/2.0, plantX, plantY) if inSubregion: if not theRegion in aPlant.subregion: aPlant.subregion.append(theRegion) #print "\nX: %f Y: %f In region: %s" % (plantX, plantY, newRegion) #print theRegion.size else: newRegion=worldBasics.garden() newRegion.name=theRegionName ###these are default values### newRegion.x=0.0 # newRegion.y=0.0 # newRegion.worldSize=1.0 # newRegion.shape='square' # ############################## ##now just read in the values# if debug: print "debug: Making attributes for region" for theRegionAttr in regionAttrs: # setattr(newRegion, theRegionAttr, theDict[theRegionAttr]) # theGarden.theRegions.append(newRegion) for aPlant in theGarden.soil: plantX=aPlant.x plantY=aPlant.y if newRegion.shape=='square': inSubregion=geometry_utils.pointInsideSquare(newRegion.x, newRegion.y, newRegion.size, plantX, plantY) elif newRegion.shape=='circle': #size needs to be radius but region defines diameter inSubregion=geometry_utils.pointInsideCircle(newRegion.x, newRegion.y, newRegion.size/2.0, plantX, plantY) if inSubregion: if not newRegion in aPlant.subregion: aPlant.subregion.append(newRegion) #print "\nX: %f Y: %f In region: %s" % (plantX, plantY, newRegion) newRegion="" theDict=[]#just clear this to free up the memory ################################################################################### theGarden.cycleNumber=cycleNumber if not showProgressBar and not runningInNodeBox: theProgressBar.update(cycleNumber) #print "%i, %i, %f, %f, %i, %f, %f, %f, %f, %f, %f" % (cycleNumber-1, theGarden.soil[0].age, theGarden.soil[0].massStem, theGarden.soil[0].massLeaf, len(theGarden.soil[0].seedList), theGarden.soil[0].massSeedsTotal, theGarden.soil[0].radiusStem, theGarden.soil[0].radiusLeaf, theGarden.soil[0].heightStem+theGarden.soil[0].heightLeafMax, theGarden.soil[0].areaPhotosynthesis, theGarden.soil[0].massFixed) ###START OF SEEING CHANGES TO SPECIES FOLDER #########Check for multiple species. If none, use default fileList=os.listdir("Species") #print fileList #ymlList=[] #print "***Checking for species...***" #for file in fileList: # theExtension=os.path.splitext(file)[1] # if theExtension==".yml": # #add this file to the list of yaml files # ymlList.append(file) # useDefaultYml=False #fileList=[] ########## if debug==1: print "number of plants: "+str(theGarden.numbPlants) if debug==1: print "number of seeds: "+str(theGarden.numbSeeds) #generate graphics if requested if produceDXFGraphics: theData=vdxfGraphics.makeDXF(theGarden) theFileName= simulationName+str(cycleNumber) vdxfGraphics.writeDXF(outputDXFGraphicsDirectory, theFileName, theData) if produceGraphics: theData=outputGraphics.makeCFDG(theView, CFDGtext, theGarden, cycleNumber) if webOutput==0: if theView==1: cfdgFileName= simulationName +"-bottom-"+str(cycleNumber) elif theView==2: cfdgFileName= simulationName +"-top-"+str(cycleNumber) elif theView==3: cfdgFileName= simulationName +"-side-"+str(cycleNumber) elif theView==12: cfdgFileName= simulationName +"-bottom-top-"+str(cycleNumber) elif theView==21: cfdgFileName= simulationName +"-top-bottom-"+str(cycleNumber) elif theView==13: cfdgFileName= simulationName +"-bottom-side-"+str(cycleNumber) elif theView==23: cfdgFileName= simulationName +"-top-side-"+str(cycleNumber) elif theView==123: cfdgFileName= simulationName +"-bottom-top-side"+str(cycleNumber) outputGraphics.writeCFDG(outputGraphicsDirectory, cfdgFileName, theData) else: cfdgFileName= simulationName outputGraphics.writeCFDG(outputGraphicsDirectory, cfdgFileName, theData) outputGraphics.outputPNGs(outputGraphicsDirectory, webDirectory) #outputGraphics.deleteCFDGFiles(outputGraphicsDirectory) ###go through the soil list and germinate seed or grow plant if theGarden.showProgressBar: print"***Allowing plants a turn to grow***" theProgressBar= progressBarClass.progressbarClass(len(theGarden.soil),"*") theBar=0 for obj in theGarden.soil[:]: if obj.isSeed: obj.germinate(theGarden) else: obj.growPlant(theGarden) if theGarden.showProgressBar: theBar=theBar+1 theProgressBar.update(theBar) ###deal with violaters of basic physics theGarden.causeRandomDeath() theGarden.checkSenescence() theGarden.removeOffWorldViolaters() theGarden.removeEulerGreenhillViolaters() theGarden.removeOverlaps() ###sort the garden.soil by height of the plants.Ordered shortest to tallest theGarden.soil= list_utils.sort_by_attr(theGarden.soil, "heightStem") ###flip the list so it's ordered tallest to shortest theGarden.soil.reverse() ###work out shading worldBasics.determineShade(theGarden) ###Calculate the amount of carbon each plant will have to start the next turn if theGarden.showProgressBar: print "***Calculating new mass from photosynthesis***" theProgressBar= progressBarClass.progressbarClass(len(theGarden.soil),"*") i=0 for plant in theGarden.soil[:]: if plant.isSeed==False: plant.massFixed=plant.calcNewMassFromLeaf(theGarden) if plant.massFixed==-1.0: plant.causeOfDeath="lack of light" theGarden.kill(plant) else: plant.massFixedRecord.append(plant.massFixed) while len(plant.massFixedRecord)>plant.numYearsGrowthMemory: plant.massFixedRecord.pop(0) if theGarden.showProgressBar: i=i+1 theProgressBar.update(i) if archive=="a": fileName=simulationName+'-'+str(cycleNumber)+'.pickle' saveSimulationPoint(saveDirectory, fileName, theGarden) if saveData=="a": fileName=simulationName+'-'+str(cycleNumber)+'.csv' saveDataPoint(dataDirectory, fileName, theGarden) #print theGarden.deathNote theGarden.deathNote=[] cycleNumber= cycleNumber+1 ###pause if you're making web graphic #if webOutput==1: # time.sleep(5) if archive=="e": fileName=simulationName+'-'+str(cycleNumber)+'.pickle' saveSimulationPoint(saveDirectory, fileName, theGarden) if saveData=="e": fileName=simulationName+'-'+str(cycleNumber)+'.csv' saveDataPoint(dataDirectory, fileName, theGarden) if produceStats: #print dataDirectory theArgument="-n '%s' -fs" % (dataDirectory+"Seeds/") print "***sending to Extract: %s" % (theArgument) os.system("python SERA_Data/vextract.py %s" % (theArgument)) theArgument="-n '%s' -fs" % (dataDirectory+"Plants/") print "***sending to Extract: %s" % (theArgument) os.system("python SERA_Data/vextract.py %s" % (theArgument)) theArgument="-n '%s' -fs" % (dataDirectory+"Corpses/") print "***sending to Extract: %s" % (theArgument) os.system("python SERA_Data/vextract.py %s" % (theArgument)) ###final graphics calls if produceGraphics==1 and webOutput==0: print "Producing PNG files..." outputGraphics.outputPNGs(outputGraphicsDirectory, outputGraphicsDirectory) if produceGraphics==1 and deleteCfdgFiles==1 and webOutput==0: print "Deleting .cfdg files..." outputGraphics.deleteCFDGFiles(outputGraphicsDirectory) ###only try and make a video if it is wanted and if pngs were made if produceVideo and produceGraphics and webOutput==0: print "Producing MOV file..." outputGraphics.outputMOV(outputGraphicsDirectory, simulationName, framesPerSecond) print "*****Simulation Complete*****" #print theGarden.deathNote #clear the values theGarden.soil=[] theGarden.deathNote=[] theGarden.cycleNumber=0 for aRegion in theGarden.theRegions: aRegion.size=0.0
def startup_script( main_globals): """ This is the main startup script for NE1. It is intended to be run only once, and only by the code in main.py. When this function returns, the caller is intended to immediately exit normally. Parameter main_globals should be the value of globals() in __main__, which is needed in case .atom-debug-rc is executed, since it must be executed in that global namespace. """ # Note: importing all of NE1's functionality can take a long time. # To the extent possible, we want that time to be spent after # something is visible to the user, but (mostly) before the main # window is shown to the user (since showing the main window implies # that NE1 is almost ready to go). So we display a splashscreen # before doing most imports and initializations, then set up most # of our data structures and UI commands (thus importing the code # needed to implement them), and then show the main window. # (Some experimental commands are initialized after that, so that # errors that occur then can't prevent the main window from becoming # visible.) # TODO: turn the sections of code below into named functions or methods, # and perhaps split before_most_imports and before_creating_app into # more named functions or methods. The biggest split should be between # functions that need to be careful to do very few or no imports, # and functions that are free to do any imports. # Windows machines spawn and remove the shell, so no info is normally # captured. This is a first attempt to try to capture some of the console # prints that would normally be lost. The default for this code is that # it's turned off, and should remain that way until it's improved. if NE1_Build_Constants.NE1_CONSOLE_REDIRECT and os.name == "nt": capture_console = False capture_file = "" # if it's not reporting as python is the executable if not sys.executable.upper().endswith("PYTHON.EXE") and \ not sys.executable.upper().endswith("PYTHON"): try: capture_file = u"".join((sys.executable[:-4], "_console.log")) sys.stdout = open(capture_file, 'w') capture_console = True # already trapped, don't try more. except: pass if not capture_console: # Haven't captured the console log yet. Find the default user # path and try to capture there this happens if we can't write to # the normal log location, or if python.exe is the executable. tmpFilePath = os.path.normpath(os.path.expanduser("~/Nanorex/")) if not os.path.exists(tmpFilePath): #If it doesn't exist try: os.mkdir(tmpFilePath) #Try making one capture_console = True except: pass # we tried, but there's no easy way to capture the console if capture_console or os.path.isdir(tmpFilePath): try: # We made the directory or it already existed, try # creating the log file. capture_file = os.path.normpath(u"".join((tmpFilePath, \ "/NE1_console.log"))) sys.stdout = open(capture_file, 'w') capture_console = True except: print >> sys.__stderr__, \ "Failed to create any console log file." capture_console = False if capture_console: # Next two lines are specifically printed to the original console print >> sys.__stdout__, "The console has been redirected into:" print >> sys.__stdout__, capture_file.encode("utf_8") print print "starting NanoEngineer-1 in [%s]," % os.getcwd(), time.asctime() print "using Python: " + sys.version try: print "on path: " + sys.executable except: pass # print the version information including official release candidate if it # is not 0 (false) if NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE: print "Version: NanoEngineer-1 v%s_RC%s" % \ (NE1_Build_Constants.NE1_RELEASE_VERSION, \ NE1_Build_Constants.NE1_OFFICIAL_RELEASE_CANDIDATE) else: print "Version: NanoEngineer-1 v%s" % \ NE1_Build_Constants.NE1_RELEASE_VERSION # "Do things that should be done before most imports occur." startup_before_most_imports.before_most_imports( main_globals ) from PyQt4.Qt import QApplication, QSplashScreen # "Do things that should be done before creating the application object." startup_before_most_imports.before_creating_app() ### TODO: this imports undo, env, debug, and it got moved earlier # in the startup process at some point. Those imports are probably not # too likely to pull in a lot of others, but if possible we should put up # the splash screen before doing most of them. Sometime try to figure out # how to do that. The point of this function is mostly to wrap every signal->slot # connection -- maybe it's sufficient to do that before creating the main # window rather than before creating the app? [bruce 071008 comment] # do some imports used for putting up splashscreen # (this must be done before any code that loads images from cad/src/ui) import utilities.icon_utilities as icon_utilities icon_utilities.initialize_icon_utilities() # Create the application object (an instance of QApplication). QApplication.setColorSpec(QApplication.CustomColor) #russ 080505: Make it global so it can be run under debugging below. global app app = QApplication(sys.argv) # Put up the splashscreen (if its image file can be found in cad/images). # # Note for developers: # If you don't want the splashscreen, just rename the splash image file. splash_pixmap = icon_utilities.imagename_to_pixmap( "images/splash.png" ) # splash_pixmap will be null if the image file was not found if not splash_pixmap.isNull(): splash = QSplashScreen(splash_pixmap) # create the splashscreen splash.show() MINIMUM_SPLASH_TIME = 3.0 # I intend to add a user pref for MINIMUM_SPLASH_TIME for A7. mark 060131. splash_start = time.time() else: print "note: splash.png was not found" # connect the lastWindowClosed signal from PyQt4.Qt import SIGNAL app.connect(app, SIGNAL("lastWindowClosed ()"), app.quit) # NOTE: At this point, it is ok to do arbitrary imports as needed, # except of experimental code. # import MWsemantics. # An old comment (I don't know if it's still true -- bruce 071008): # this might have side effects other than defining things. from ne1_ui.MWsemantics import MWsemantics # initialize modules and data structures from ne1_startup import startup_misc # do this here, not earlier, so it's free to do whatever toplevel imports it wants # [bruce 071008 change] startup_misc.call_module_init_functions() startup_misc.register_MMP_RecordParsers() # do this before reading any mmp files # create the single main window object foo = MWsemantics() # This does a lot of initialization (in MainWindow.__init__) import __main__ __main__.foo = foo # developers often access the main window object using __main__.foo when debugging, # so this is explicitly supported # initialize CoNTubGenerator # TODO: move this into one of the other initialization functions #Disabling the following code that initializes the ConTub plugin #(in UI it is called Heterojunction.) The Heterojunction generator or #ConTubGenerator was never ported to Qt4 platform. The plugin generator #needs a code cleanup -- ninad 2007-11-16 ##import CoNTubGenerator ##CoNTubGenerator.initialize() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *before* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_pre_main_show except NameError: pass else: func() # Do other things that should be done just before showing the main window startup_misc.pre_main_show(foo) # this sets foo's geometry, among other things foo._init_after_geometry_is_set() if not splash_pixmap.isNull(): # If the MINIMUM_SPLASH_TIME duration has not expired, sleep for a moment. while time.time() - splash_start < MINIMUM_SPLASH_TIME: time.sleep(0.1) splash.finish( foo ) # Take away the splashscreen # show the main window foo.show() # for developers: run a hook function that .atom-debug-rc might have defined # in this module's global namespace, for doing things *after* showing the # main window. try: # do this, if user asked us to by defining it in .atom-debug-rc func = atom_debug_post_main_show except NameError: pass else: func() # do other things after showing the main window startup_misc.post_main_show(foo) # start psyco runtime optimizer (EXPERIMENTAL) -- # for doc see http://psyco.sourceforge.net/ # # Example: it speeds up code like this by 17 times: # (in my test, Intel Mac OS 10.4, Python 2.4.4) # x = 17 # for i in range(10**7): # x += i % 3 - 1 # # [bruce 080524] from utilities.debug_prefs import debug_pref, Choice_boolean_False if debug_pref("Use psyco runtime optimizer (next session)?", Choice_boolean_False, prefs_key = True ): # Import Psyco if available try: import psyco ## psyco.full() -- insert dna takes a lot of time, then segfaults # after printing "inside this what's this"; # plan: be more conservative about what it should optimize... # preferably bind specific functions using psyco.bind(). # For now, just tell it to only optimize the most important ones. psyco.log() # manual says: log file name looks like xxx.log-psyco # by default, where xxx is the name of the script you ran # (when I ran "python main.py" in cad/src, it wrote to main.log-psyco there) # (maybe we can pass our own pathname as an argument?) ## psyco.profile(0.2) # use profiling, optimize funcs that use # more than 20% of the time (not sure what that means exactly) # (seems safe, but from log file, i guess it doesn't do much) psyco.profile(0.05) # "aggressive" print "using psyco" pass except ImportError: print "not using psyco" pass pass # Decide whether to do profiling, and if so, with which # profiling command and into what file. Set local variables # to record the decision, which are used later when running # the Qt event loop. # If the user's .atom-debug-rc specifies PROFILE_WITH_HOTSHOT = True, # use hotshot, otherwise fall back to vanilla Python profiler. # (Note: to work, it probably has to import this module # and set this variable in this module's namespace.) try: PROFILE_WITH_HOTSHOT except NameError: PROFILE_WITH_HOTSHOT = False try: # user can set atom_debug_profile_filename to a filename in .atom-debug-rc, # to enable profiling into that file. For example: # % cd # % cat > .atom-debug-rc # atom_debug_profile_filename = '/tmp/profile-output' # ^D # ... then run NE1, and quit it # ... then in a python shell: # import pstats # p = pstats.Stats('<filename>') # p.strip_dirs().sort_stats('time').print_stats(100) # order by internal time (top 100 functions) # p.strip_dirs().sort_stats('cumulative').print_stats(100) # order by cumulative time atom_debug_profile_filename = main_globals.get('atom_debug_profile_filename') if atom_debug_profile_filename: print ("\nUser's .atom-debug-rc requests profiling into file %r" % (atom_debug_profile_filename,)) if not type(atom_debug_profile_filename) in [type("x"), type(u"x")]: print "error: atom_debug_profile_filename must be a string" assert 0 # caught and ignored, turns off profiling if PROFILE_WITH_HOTSHOT: try: import hotshot except: print "error during 'import hotshot'" raise # caught and ignored, turns off profiling else: try: import cProfile as py_Profile except ImportError: print "Unable to import cProfile. Using profile module instead." py_Profile = None if py_Profile is None: try: import profile as py_Profile except: print "error during 'import profile'" raise # caught and ignored, turns off profiling except: print "exception setting up profiling (hopefully reported above); running without profiling" atom_debug_profile_filename = None # Create a fake "current exception", to help with debugging # (in case it's shown inappropriately in a later traceback). # One time this is seen is if a developer inserts a call to print_compact_traceback # when no exception is being handled (instead of the intended print_compact_stack). try: assert 0, "if you see this exception in a traceback, it is from the" \ " startup script called by main.py, not the code that printed the traceback" except: pass # Handle a mmp file passed to it via the command line. The mmp file # must be the first argument (after the program name) found on the # command line. All other arguments are currently ignored and only # one mmp file can be loaded from the command line. # old revision with --initial-file is at: svn rev 12759 # Derrick 20080520 if ((len(sys.argv) >= 2) and sys.argv[1].endswith(".mmp")): foo.fileOpen(sys.argv[1]) # Do other post-startup, pre-event-loop, non-profiled things, if any # (such as run optional startup commands for debugging). startup_misc.just_before_event_loop() if os.environ.has_key('WINGDB_ACTIVE'): # Hack to burn some Python bytecode periodically so Wing's # debugger can remain responsive while free-running # [from http://wingware.com/doc/howtos/pyqt; added by bruce 081227] # Addendum [bruce 090107]: this timer doesn't noticeably slow down NE1, # but with or without it, NE1 is about 4x slower in Wing than running # alone, at least when running test_selection_redraw.py. print "running under Wing IDE debugger; setting up timer" from PyQt4 import QtCore timer = QtCore.QTimer() def donothing(*args): x = 0 for i in range(0, 100): x += i timer.connect(timer, QtCore.SIGNAL("timeout()"), donothing) timer.start(200) # Finally, run the main Qt event loop -- # perhaps with profiling, depending on local variables set above. # This does not normally return until the user asks NE1 to exit. # Note that there are three copies of the statement which runs that loop, # two inside string literals, all of which presumably should be the same. if atom_debug_profile_filename: if PROFILE_WITH_HOTSHOT: profile = hotshot.Profile(atom_debug_profile_filename) profile.run('app.exec_()') else: py_Profile.run('from ne1_startup.main_startup import app; app.exec_()', atom_debug_profile_filename) print ("\nProfile data was presumably saved into %r" % (atom_debug_profile_filename,)) else: # if you change this code, also change both string literals just above app.exec_() # Now return to the caller in order to do a normal immediate exit of NE1. return # from startup_script
if g.app.killed: return # Support for g.app.forceShutdown. # Create the default gui if needed. if g.app.gui == None: g.app.createSwingGui() # Creates global windows. # Initialize tracing and statistics. #g.init_sherlock(args) #g.clear_stats() #@ << start psycho >> #@+node:orkman.20050213174452.4:<< start psycho >> if g.app and g.app.use_psyco: try: import psyco if 0: theFile = r"c:\prog\test\psycoLog.txt" g.es("psyco now logging to",theFile,color="blue") psyco.log(theFile) psyco.profile() psyco.full() g.es("psyco now running",color="blue") except ImportError: pass except: print "unexpected exception importing psyco" g.es_exception() #@nonl #@-node:orkman.20050213174452.4:<< start psycho >> #@nl # Create the main frame. Show it and all queued messages. c,frame = createFrame(fileName) if not frame: return if g.app.disableSave:
def run(fileName=None,*args,**keywords): """Initialize and run Leo""" __pychecker__ = '--no-argsused' # keywords not used. if not isValidPython(): return #@ << import leoGlobals and leoApp >> #@+node:ekr.20041219072112:<< import leoGlobals and leoApp >> # Import leoGlobals, but do NOT set g. try: import leoGlobals except ImportError: print "Error importing leoGlobals.py" # Create the application object. try: import leoApp leoGlobals.app = leoApp.LeoApp() except ImportError: print "Error importing leoApp.py" # NOW we can set g. g = leoGlobals assert(g.app) #@nonl #@-node:ekr.20041219072112:<< import leoGlobals and leoApp >> #@nl g.computeStandardDirectories() script, windowFlag = getBatchScript() # Do early so we can compute verbose next. verbose = script is None g.app.setLeoID(verbose=verbose) # Force the user to set g.app.leoID. #@ << import leoNodes and leoConfig >> #@+node:ekr.20041219072416.1:<< import leoNodes and leoConfig >> try: import leoNodes except ImportError: print "Error importing leoNodes.py" import traceback ; traceback.print_exc() try: import leoConfig except ImportError: print "Error importing leoConfig.py" import traceback ; traceback.print_exc() #@nonl #@-node:ekr.20041219072416.1:<< import leoNodes and leoConfig >> #@nl g.app.nodeIndices = leoNodes.nodeIndices(g.app.leoID) g.app.config = leoConfig.configClass() fileName = completeFileName(fileName) reportDirectories(verbose) # Read settings *after* setting g.app.config. # Read settings *before* opening plugins. This means if-gui has effect only in per-file settings. g.app.config.readSettingsFiles(fileName,verbose) g.app.setEncoding() if script: if windowFlag: g.app.createTkGui() # Creates global windows. g.app.gui.setScript(script) sys.args = [] else: createNullGuiWithScript(script) fileName = None # Load plugins. Plugins may create g.app.gui. g.doHook("start1") if g.app.killed: return # Support for g.app.forceShutdown. # Create the default gui if needed. if g.app.gui == None: g.app.createTkGui() # Creates global windows. # Initialize tracing and statistics. g.init_sherlock(args) #@ << start psycho >> #@+node:ekr.20040411081633:<< start psycho >> if g.app and g.app.use_psyco: try: import psyco if 0: theFile = r"c:\prog\test\psycoLog.txt" g.es("psyco now logging to",theFile,color="blue") psyco.log(theFile) psyco.profile() psyco.full() g.es("psyco now running",color="blue") except ImportError: pass except: print "unexpected exception importing psyco" g.es_exception() #@nonl #@-node:ekr.20040411081633:<< start psycho >> #@nl # New in 4.3: clear g.app.initing _before_ creating the frame. g.app.initing = False # "idle" hooks may now call g.app.forceShutdown. # Create the main frame. Show it and all queued messages. c,frame = createFrame(fileName) if not frame: return g.app.trace_gc = c.config.getBool('trace_gc') g.app.trace_gc_calls = c.config.getBool('trace_gc_calls') g.app.trace_gc_verbose = c.config.getBool('trace_gc_verbose') if g.app.disableSave: g.es("disabling save commands",color="red") g.app.writeWaitingLog() p = c.currentPosition() g.doHook("start2",c=c,p=p,v=p,fileName=fileName) if c.config.getBool('allow_idle_time_hook'): g.enableIdleTimeHook() if not fileName: c.redraw_now() c.bodyWantsFocus() g.app.gui.runMainLoop()
"""This file is part of Vida. -------------------------- Copyright 2009, Sean T. Hammond Vida is experimental in nature and is made available as a research courtesy "AS IS," but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. You should have received a copy of academic software agreement along with Vida. If not, see <http://iorek.ice-nine.org/seant/Vida/license.txt>. """ import math #Import Psyco if possible try: import psyco psyco.log() psyco.full() except ImportError: pass def checkOverlap(x, y, r, xx, yy, rr): return circleOverlap(x,y,r,xx,yy,rr) def python_circle_circle_overlap(x,y,r,xx,yy,rr): theDistance =distBetweenPoints(x, y, xx, yy) ###now look at the distance in relation to the radii if theDistance>(r+rr): ###no overlap return 0 elif theDistance<(math.fabs(r-rr)): ###complete overlap return 1
def start_loop(self, companyName=None, companyCapital=None, loadPreviousGame=None): """ companyName string of a company that will play as current player. If none, the game will run in simulation mode companyCapital int with the starting capital of the newly started company. loadPreviousGame filename of a save game that can be loaded """ #initilizing screen stuff window_size = global_variables.window_size pygame.init() if global_variables.fullscreen: window = pygame.display.set_mode(window_size, FULLSCREEN) else: window = pygame.display.set_mode(window_size) icon = pygame.image.load(os.path.join("images", "window_icon.png")) pygame.display.set_icon(icon) pygame.mouse.set_cursor(*pygame.cursors.arrow) #initializing the world - depends on if a previous game should be loaded if loadPreviousGame is not None: sol = solarsystem.solarsystem(global_variables.start_date, de_novo_initialization=False) sol.load_solar_system(loadPreviousGame) else: sol = solarsystem.solarsystem(global_variables.start_date, de_novo_initialization=True) #initialize current player company if companyName is not None: if sol.current_player is not None: raise Exception( "The loaded solar system already had a current player") automation_dict = { "Demand bidding (initiate buying bids)": False, "Supply bidding (initiate selling bids)": False, "Asset market (buy bases and firms)": False, "Commodities market (start commodity producing firms)": False, "Tech market (buy and sell technology)": False, "Transport market (start up merchant firms)": False, "Evaluate firms (close problematic firms)": False, "Start research firms": False, "Pick research (pick research automatically)": False, "Expand area of operation (search for new home cities)": False } if companyName in sol.companies.keys(): sol.current_player = sol.companies[companyName] sol.current_player.automation_dict = automation_dict sol.current_player.automation_dict[ "Demand bidding (initiate buying bids)"] = True sol.current_player.automation_dict[ "Supply bidding (initiate selling bids)"] = True sol.current_player.capital = companyCapital else: model_companyName = random.choice(sol.companies.keys()) model_company = sol.companies[model_companyName] new_company = company.company(sol, model_company.company_database, deviation=5, companyName=companyName, capital=companyCapital) sol.companies[companyName] = new_company new_company.automation_dict = automation_dict sol.current_player = new_company #loading planets that are often used: print "loading earth" sol.planets["earth"].pickle_all_projections() print "finished loading" #divide the surface in action and non-action action_rect = pygame.Rect(0, 0, global_variables.window_size[0] - 150, global_variables.window_size[1] - 100) right_side_rect = pygame.Rect(global_variables.window_size[0] - 150, 0, 150, global_variables.window_size[1]) message_rect = pygame.Rect(10, global_variables.window_size[1] - 100, global_variables.window_size[0] - 170, 100) action_surface = window.subsurface(action_rect) right_side_surface = window.subsurface(right_side_rect) message_surface = window.subsurface(message_rect) #switch to determine planetary mode or solarsystem mode from beginning mode_before_change = sol.display_mode if sol.display_mode == "solar_system": surface = sol.draw_solar_system( zoom_level=sol.solar_system_zoom, date_variable=sol.current_date, center_object=sol.current_planet.planet_name) if sol.display_mode == "planetary": sol.current_planet = sol.planets["earth"] surface = sol.current_planet.draw_entire_planet( sol.current_planet.eastern_inclination, sol.current_planet.northern_inclination, sol.current_planet.projection_scaling) action_surface.blit(surface, (0, 0)) pygame.display.flip() #Initialising the GUI gui_instance = gui.gui(right_side_surface, message_surface, action_surface, sol) #getting psyco if available try: import psyco psyco.log() psyco.profile() except ImportError: pass i = 0 sol.launchThread() while True: # print "Game running another gui cycle" events = pygame.event.get() for event in events: if event.type == QUIT: sys.exit(0) if event.type == 5: #mouse down event gui_instance.receive_click(event) pygame.display.flip() if event.type == 2: #key down event if "text_receiver" in dir(gui_instance.active_window): if gui_instance.active_window.text_receiver is not None: gui_instance.active_window.text_receiver.receive_text( event) break if event.key == 280: #pgup gui_instance.zoom_in(event) if event.key == 281: #pgdown gui_instance.zoom_out(event) if event.key == 276: #left gui_instance.go_left(event) if event.key == 275: #right gui_instance.go_right(event) if event.key == 273: #up gui_instance.go_up(event) if event.key == 274: #down gui_instance.go_down(event) pygame.display.flip() i = 0 gui_instance.create_infobox() gui_instance.all_windows["Messages"].create() #in solar system the display needs updating all the time. However we need to protect whatever active window is shown: if sol.display_mode == "solar_system": surface = sol.draw_solar_system( zoom_level=sol.solar_system_zoom, date_variable=sol.current_date, center_object=sol.current_planet.planet_name) if gui_instance.active_window is not None: left_rect = pygame.Rect(0, 0, gui_instance.active_window.rect[0], global_variables.window_size[1]) right_rect = pygame.Rect( gui_instance.active_window.rect[0] + gui_instance.active_window.rect[2], 0, global_variables.window_size[0] - gui_instance.active_window.rect[0] - gui_instance.active_window.rect[2], global_variables.window_size[1]) top_rect = pygame.Rect(0, 0, global_variables.window_size[0], gui_instance.active_window.rect[1]) bottom_rect = pygame.Rect( 0, gui_instance.active_window.rect[1] + gui_instance.active_window.rect[3], global_variables.window_size[0], global_variables.window_size[1] - gui_instance.active_window.rect[3] - top_rect[3]) for rect in [left_rect, right_rect, top_rect, bottom_rect]: action_surface.set_clip(rect) action_surface.blit(surface, (0, 0)) action_surface.set_clip(None) else: action_surface.blit(surface, (0, 0)) pygame.display.flip()
for i in range(self.NbChannels)]) + '\n') #--------------------------- def main(): dt = 0.001 THFC = thalamusFC('CBG', 6) saliences = numpy.zeros((6)) saliences[0] = 0.4 BG_Input = numpy.zeros((6)) for t in range(200): THFC.stepCompute(dt, saliences, BG_Input) THFC.logAll() #--------------------------- if __name__ == '__main__': # Import Psyco if available try: import psyco psyco.log() psyco.profile() psyco.full() except ImportError: print('Psyco not available.') main()
########################################################################################################## # On crée d'abord la variable d'environnement HOME qui peut être nécessaire à matplotlib import user os.environ['HOME'] = globdef.APP_DATA_PATH print "user.home", user.home import Principal if __name__ == "__main__": if globdef.PSYCO: from CedWidgets import chronometrer try: import psyco HAVE_PSYCO = True except: HAVE_PSYCO = False if HAVE_PSYCO: # import psyco ; psyco.jit() # from psyco.classes import * print "Psyco !!!" if globdef.DEBUG: PSYCO_LOG = os.path.join(globdef.APP_DATA_PATH, sys.argv[0] + '.log-psyco') psyco.log(logfile=PSYCO_LOG) psyco.profile() psyco.full() App = PySylicApp(0) App.MainLoop()