Ejemplo n.º 1
0
def menu():
	initialize()
	while 1:
		usr_inp=raw_input("brutus>")

		if usr_inp=="":
			usr_inp=raw_input("brutus>")

		elif usr_inp=="quit" or usr_inp=="exit":
			quit()

		elif usr_inp=="help":
			print("\n")
			help()	

		elif usr_inp=="clear":
			os.system("clear")
		
		elif usr_inp=="ssh":
			ssh_brute()

		elif usr_inp=="ftp":
			ftp_brute()

		elif usr_inp=="smtp":
			smtp()

		elif usr_inp=="facebook":
			facebook_brute()

		elif usr_inp=="twitter":
			twitter_brute()

		else:
			print(usr_inp+": command not recognised ~brutus")
Ejemplo n.º 2
0
def calibrate():
    initialize()
    motor['C'].on_for_rotations(25, -2.5)

    def thread1():
        while True:
            sleep(0.25)
            carriage_move(0)
            variables['LinePosition'] = 0
            sleep(0.25)
            line_width = variables['LineWidth']
            carriage_move(line_width)
            variables['LinePosition'] = line_width
            if buttons.test((CENTER, ), State.BUMPED):
                break
        carriage_move(525)
        motor['C'].on_for_rotations(25, 3)

    def thread2():
        while True:
            buttons.wait((UP, CENTER, DOWN), State.PRESSED)
            button = buttons.read()
            if button == UP:
                motor['C'].on_for_degrees(25, 5)
            elif button == DOWN:
                motor['C'].on_for_degrees(-25, 5)
            elif button == CENTER:
                # This is not in the EV3-G program, but is needed in order for
                # the program to exit, otherwise this thread keeps running.
                raise SystemExit

    fork(thread1, thread2)
Ejemplo n.º 3
0
def r8_uniform_01():

    #*****************************************************************************80
    #
    ## R8_UNIFORM_01 returns a uniform random real number in [0,1].
    #
    #  Discussion:
    #
    #    This procedure returns a random floating point number from a uniform
    #    distribution over (0,1), not including the endpoint values, using the
    #    current random number generator.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    27 May 2013
    #
    #  Author:
    #
    #    Original Pascal version by Pierre L'Ecuyer, Serge Cote.
    #    MATLAB version by John Burkardt.
    #
    #  Reference:
    #
    #    Pierre LEcuyer, Serge Cote,
    #    Implementing a Random Number Package with Splitting Facilities,
    #    ACM Transactions on Mathematical Software,
    #    Volume 17, Number 1, March 1991, pages 98-111.
    #
    #  Parameters:
    #
    #    Output, real R8_UNIFORM_01, a uniform random value in [0,1].
    #
    from i4_uniform import i4_uniform
    from initialize import initialize
    from initialized_get import initialized_get
    #
    #  Check whether the package must be initialized.
    #
    if (not initialized_get()):
        print ''
        print 'R8_UNIFORM_01 - Note:'
        print '  Initializing RNGLIB package.'
        initialize()


#
#  Get a random positive integer.
#
    i = i4_uniform()
    #
    #  Scale it to a random real in [0,1].
    #
    value = i * 4.656613057E-10

    return value
Ejemplo n.º 4
0
def test(img_path: str = 'data/custom/images/', anno_path: str = 'data/custom/annos/') -> None:
    # transform something
    initialize(img_path=img_path, anno_path=anno_path, split_ratio=1.0)

    # some common config
    iou_thres = 0.5
    conf_thres = 0.01
    nms_thres = 0.5
    img_size = 416
    batch_size = 16
    device = tc.device('cuda' if tc.cuda.is_available() else 'cpu')

    # other paths
    weights_path = 'my/yolov3_ckpt_1.pth'
    model_def = 'config/custom.cfg'
    test_path = 'data/custom/train.txt'
    class_path = 'data/custom/classes.names'

    # load model
    class_names = load_classes(class_path)
    model = Darknet(model_def).to(device)
    model.load_state_dict(tc.load(weights_path))


    imgs, img_detections = detect(
            model=model,
            path=img_path,
            conf_thres=conf_thres,
            nms_thres=nms_thres,
            img_size=img_size,
            batch_size=batch_size,
            n_cpu=8,
            device=device,
        )

        os.makedirs('predicted_file', exist_ok=True)

        class1 = open('predicted_file/det_test_core.txt', 'w')
        class2 = open('predicted_file/det_test_coreless.txt', 'w')
        for path, boxes in zip(imgs, img_detections):
            w, h = Image.open(path).size
            boxes = rescale_boxes(boxes, img_size, (h, w))
            for box in boxes:
                line = [
                    # os.path.split(path)[1].split('_')[1].split('.')[0],  # no prefix
                    os.path.split(path)[1].split('.')[0],  # with prefix 'core_' or 'coreless_'
                    f'{box[4].tolist():.3f}',  # conf
                    f'{box[0].tolist():.1f}',
                    f'{box[1].tolist():.1f}',
                    f'{box[2].tolist():.1f}',
                    f'{box[3].tolist():.1f}',
                ]
                if box[-1] == 0.0:
                    class1.write(' '.join(line) + '\n')
                elif box[-1] == 1.0:
                    class2.write(' '.join(line) + '\n')
        class1.close()
        class2.close()
        print('Output file saved.\n')
Ejemplo n.º 5
0
def r4_uniform_01 ( ):

#*****************************************************************************80
#
## R4_UNIFORM_01 returns a uniform random real number in [0,1].
#
#  Discussion:
#
#    This procedure returns a random floating point number from a uniform
#    distribution over (0,1), not including the endpoint values, using the
#    current random number generator.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    Original Pascal version by Pierre L'Ecuyer, Serge Cote.
#    MATLAB version by John Burkardt.
#
#  Reference:
#
#    Pierre LEcuyer, Serge Cote,
#    Implementing a Random Number Package with Splitting Facilities,
#    ACM Transactions on Mathematical Software,
#    Volume 17, Number 1, March 1991, pages 98-111.
#
#  Parameters:
#
#    Output, real R4_UNIFORM_01, a uniform random value in [0,1].
#
  from i4_uniform import i4_uniform
  from initialize import initialize
  from initialized_get import initialized_get
#
#  Check whether the package must be initialized.
#
  if ( not initialized_get ( ) ):
    print ''
    print 'R4_UNIFORM_01 - Note:'
    print '  Initializing RNGLIB package.'
    initialize ( )
#
#  Get a random positive integer.
#
  i = i4_uniform ( )
#
#  Scale it to a random real in [0,1].
#
  value = i * 4.656613057E-10

  return value
Ejemplo n.º 6
0
def get_state():

    #*****************************************************************************80
    #
    ## GET_STATE returns the state of the current generator.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    27 May 2013
    #
    #  Author:
    #
    #    Original Pascal version by Pierre L'Ecuyer, Serge Cote.
    #    PYTHON version by John Burkardt.
    #
    #  Reference:
    #
    #    Pierre LEcuyer, Serge Cote,
    #    Implementing a Random Number Package with Splitting Facilities,
    #    ACM Transactions on Mathematical Software,
    #    Volume 17, Number 1, March 1991, pages 98-111.
    #
    #  Parameters:
    #
    #    Output, integer CG1, CG2, the CG values for the current generator.
    #
    from cg_get import cg_get
    from cgn_get import cgn_get
    from initialize import initialize
    from initialized_get import initialized_get
    #
    #  Check whether the package must be initialized.
    #
    if (not initialized_get()):
        print ''
        print 'GET_STATE - Note:'
        print '  Initializing RNGLIB package.'
        initialize()


#
#  Get the current generator index.
#
    g = cgn_get()
    #
    #  Retrieve the seed values for this generator.
    #
    [cg1, cg2] = cg_get(g)

    return cg1, cg2
Ejemplo n.º 7
0
def get_state ( ):

#*****************************************************************************80
#
## GET_STATE returns the state of the current generator.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    Original Pascal version by Pierre L'Ecuyer, Serge Cote.
#    PYTHON version by John Burkardt.
#
#  Reference:
#
#    Pierre LEcuyer, Serge Cote,
#    Implementing a Random Number Package with Splitting Facilities,
#    ACM Transactions on Mathematical Software,
#    Volume 17, Number 1, March 1991, pages 98-111.
#
#  Parameters:
#
#    Output, integer CG1, CG2, the CG values for the current generator.
#
  from cg_get import cg_get
  from cgn_get import cgn_get
  from initialize import initialize
  from initialized_get import initialized_get
#
#  Check whether the package must be initialized.
#
  if ( not initialized_get ( ) ):
    print ''
    print 'GET_STATE - Note:'
    print '  Initializing RNGLIB package.'
    initialize ( )
#
#  Get the current generator index.
#
  g = cgn_get ( )
#
#  Retrieve the seed values for this generator.
#
  [ cg1, cg2 ] = cg_get ( g )

  return cg1, cg2
Ejemplo n.º 8
0
def rnglib_test01():

    #*****************************************************************************80
    #
    ## RNGLIB_TEST01 calls I4_UNIFORM 10 times, just to show how it is done.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    27 May 2013
    #
    #  Author:
    #
    #    John Burkardt
    #
    from cgn_set import cgn_set
    from i4_uniform import i4_uniform
    from initialize import initialize

    print ''
    print 'RNGLIB_TEST01'
    print '  I4_UNIFORM ( ) returns a random positive integer'
    print '  using the current generator.'
    #
    #  Initialize the package.
    #
    print ''
    print '  INITIALIZE initializes the random number generator.'
    print '  It only needs to be called once before using the package.'

    initialize()
    #
    #  Set the current generator index to #1.
    #
    g = 1
    cgn_set(g)
    print ''
    print '  Current generator index = %d' % (g)
    #
    #  Now call I4_UNIFORM().
    #
    print ''
    print '   I     I4_UNIFORM ( )'
    print ''

    for i in range(1, 11):
        j = i4_uniform()
        print '  %2d  %12d' % (i, j)
Ejemplo n.º 9
0
def rnglib_test01 ( ):

#*****************************************************************************80
#
## RNGLIB_TEST01 calls I4_UNIFORM 10 times, just to show how it is done.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license. 
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    John Burkardt
#
  from cgn_set import cgn_set
  from i4_uniform import i4_uniform
  from initialize import initialize

  print ''
  print 'RNGLIB_TEST01'
  print '  I4_UNIFORM ( ) returns a random positive integer'
  print '  using the current generator.'
#
#  Initialize the package.
#
  print ''
  print '  INITIALIZE initializes the random number generator.'
  print '  It only needs to be called once before using the package.'

  initialize ( )
#
#  Set the current generator index to #1.
#
  g = 1
  cgn_set ( g )
  print ''
  print '  Current generator index = %d' % ( g )
#
#  Now call I4_UNIFORM().
#
  print ''
  print '   I     I4_UNIFORM ( )'
  print ''

  for i in range ( 1, 11 ):
    j = i4_uniform ( )
    print '  %2d  %12d' % ( i, j )
Ejemplo n.º 10
0
def rnglib_test02():

    #*****************************************************************************80
    #
    ## RNGLIB_TEST02 calls R4_UNIFORM_01 10 times, just to show how it is done.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    27 May 2013
    #
    #  Author:
    #
    #    John Burkardt
    #
    from cgn_set import cgn_set
    from initialize import initialize
    from r4_uniform_01 import r4_uniform_01

    print ''
    print 'RNGLIB_TEST02'
    print '  R4_UNIFORM_01 ( ) returns a random real number'
    print '  in [0,1] using the current generator.'
    #
    #  Initialize the package.
    #
    print ''
    print '  INITIALIZE initializes the random number generator.'
    print '  It only needs to be called once before using the package.'

    initialize()
    #
    #  Set the current generator index to #2.
    #
    g = 2
    cgn_set(g)
    print ''
    print '  Current generator index = %d' % (g)
    #
    #  Repeatedly call R4_UNIFORM_01().
    #
    print ''
    print '   I     R4_UNIFORM_01 ( )'
    print ''

    for i in range(1, 11):
        u = r4_uniform_01()
        print '  %2d  %14.6g' % (i, u)
Ejemplo n.º 11
0
def rnglib_test02 ( ):

#*****************************************************************************80
#
## RNGLIB_TEST02 calls R4_UNIFORM_01 10 times, just to show how it is done.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license. 
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    John Burkardt
#
  from cgn_set import cgn_set
  from initialize import initialize
  from r4_uniform_01 import r4_uniform_01

  print ''
  print 'RNGLIB_TEST02'
  print '  R4_UNIFORM_01 ( ) returns a random real number'
  print '  in [0,1] using the current generator.'
#
#  Initialize the package.
#
  print ''
  print '  INITIALIZE initializes the random number generator.'
  print '  It only needs to be called once before using the package.'

  initialize ( )
#
#  Set the current generator index to #2.
#
  g = 2
  cgn_set ( g )
  print ''
  print '  Current generator index = %d' % ( g )
#
#  Repeatedly call R4_UNIFORM_01().
#
  print ''
  print '   I     R4_UNIFORM_01 ( )'
  print ''

  for i in range ( 1, 11 ):
    u = r4_uniform_01 ( )
    print '  %2d  %14.6g' % ( i, u )
Ejemplo n.º 12
0
def main():

    if initialize(version=__version__):

        # Primary
        while True:
            main_loop()
Ejemplo n.º 13
0
 def startGame(self):
     self.stopB.configure(state="normal")
     self.pauseB.configure(state="normal")
     self.startB.configure(state="disabled")
     self.gameRunning = True
     self.gameOver = False
     self.gameScore = 0
     initialize.initialize(self.canvas)
     #self.player = self.canvas.create_rectangle(100,100,200,200)
     #self.canvas.addtag_closest("player",100,100)
     #self.master.bind("<Key>",self.keyPress)
     self.currentFrameIndex = 1
     self.keyF = len(self.key)*[-setupVars.deadFrames]
     self.currentFrameLabel.configure(text="Frame: {}".format(self.currentFrameIndex))
     self.key = [0,0,0,0]
     self.updateGame()
Ejemplo n.º 14
0
def main():
    file_dict = initialize.initialize()
    logger = logging.Logger("primary_driver", level=logging.INFO)

    sensor_watcher = SensorWatcher()
    point_cloud_generator = PointCloudGenerator(POINT_CLOUD_FILE_NAME, TARGET_LOCATIONS_FILE_NAME)
    real_time_visualizer = RealTimeVisualizer(POINT_CLOUD_FILE_NAME)

    sensor_watcher.add_subscriber(point_cloud_generator)
    point_cloud_generator.add_subscriber(real_time_visualizer)

    sensor_watcher.begin()

    while not sensor_watcher.finished:
        time.sleep(1)

    data_filterer = DataFilterer(file_dict)
    mesh_generator = MeshGenerator(file_dict)

    data_filterer.begin()

    while not data_filterer.finished:
        time.sleep(1)

    mesh_generator.begin()

    while not mesh_generator.finished:
        time.sleep(1)

    logger.info("Completed all ATLAS software :)")
Ejemplo n.º 15
0
def main():
    args = get_args()
    wandb.init()
    wandb.config.update(args)

    seed = 42
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.deterministic = True
    torch.backends.cudnn.benchmark = False

    loaded_model = False

    [train_loader, valid_loader, model,
     optimizer] = initialize(args, loaded_model)
    scaler = torch.cuda.amp.GradScaler()

    wandb.watch(model)
    best_acc = 0
    run_avg = RunningAverage()

    # scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min')
    # scheduler = torch.optim.lr_scheduler.CyclicLR(optimizer, base_lr=0.001, max_lr=0.1, cycle_momentum=False)

    for epoch in range(1, args.epochs_number + 1):
        run_avg.reset_train()
        run_avg.reset_val()

        train(args, model, train_loader, epoch, optimizer, scaler, run_avg)
        val_acc = evaluation(args, model, valid_loader, epoch, run_avg)

        # scheduler.step()
        if best_acc < val_acc:
            best_acc = val_acc
            save_checkpoint(model, optimizer, args, epoch)
def main(server=SERVER, me=ME, you=YOU):
    # init MQTT
    c = MQTTClient(me, server)
    c.set_callback(handle_message)
    c.connect()
    c.subscribe(('ev3dev-telegraph-net/' + you).encode())
    topic = ('ev3dev-telegraph-net/' + me).encode()

    # init printer
    initialize()
    feed_in()

    def thread1():
        """Continuously process the queue of letters."""
        motor['C'].on_for_rotations(50, -2.5)
        carriage_move(0)
        process_queue()
        carriage_move(525)

        def thread1_1():
            motor['C'].on_for_rotations(50, 2.5)

        def thread1_2():
            feed_out()

        fork(thread1_1, thread1_2)

    def thread2():
        """Continuously monitor the touch sensor and convert the Morse code
        sequence into a letter index which gets published.
        """
        read_code(lambda l: c.publish(topic, bytes((l, ))))

    def thread3():
        """This will wait for any MQTT messages, and add them to the letter
        queue via handle_message().
        """
        while True:
            try:
                c.wait_msg()
            except OSError as err:
                if err.args[0] == EINTR:
                    continue
                raise

    fork(thread1, thread2, thread3)
Ejemplo n.º 17
0
def simSeason(schedules, east, depth_df, pca_s, pca_b, RF, teams, win_prob_power, injury_freq, injury_print=False):
    global injuries
    global depth
    standings, injuries, depth_df = initialize(schedules, east, depth_df)
    season = pd.concat(schedules.apply(lambda x: runGame(depth_df, injuries, x, injury_freq, injury_print), axis=1).values.tolist()).sort_values('gmDateTime').reset_index(drop=True)
    season = aggWinner(season, pca_s, pca_b, RF, win_prob_power)
    for team in teams:
        standings[team]['W'] = season[season['teamAbbr']==team].IsWinner.sum()
        standings[team]['L'] = 82-season[season['teamAbbr']==team].IsWinner.sum()
    return(season, injuries, standings)
Ejemplo n.º 18
0
def main():
    # Initialize the data network to be the correct size/ shape
    nodes = initialize(networkfile)

    # Run through the actual simulation stuff
    results = solve(nodes, 1.0e-6)

    # Display the results
    for node in results:
        printNode(node)
Ejemplo n.º 19
0
def main():
    file_dict = initialize.initialize()
    logger = logging.Logger("primary_driver", level=logging.INFO)

    mesh_generator = MeshGenerator(file_dict)

    mesh_generator.begin()

    while not mesh_generator.finished:
        time.sleep(1)
        logger.info("Completed all ATLAS software :)")
Ejemplo n.º 20
0
 def __init__(self, league):
     """
     Create self.batters and self.pitchers, lists where every entry
     represnts a fantasy team.  These are ordered by league team number.
     Each entry is a dictionary of statistics for that team.
     """
     startv = initialize('roto.ini')
     self.batters = []
     self.pitchers = []
     for tmno in range(0,12):
         tmdata = log_team(league, tmno+1)
         self.batters.append(get_extrap(tmdata[0], startv['totalg'], startv['sofar']))
         self.pitchers.append(get_extrap(tmdata[1], startv['totalg'], startv['sofar']))
Ejemplo n.º 21
0
    def __init__(self,
                 path,
                 filepath,
                 executable,
                 fuzzer,
                 use_default=True,
                 prototype=''):
        """
        path => Path to the root directory of source to be fuzzed
        filepath => Relative path of file containing main from root directory
                of source
        executable => Name of final executable generated
        fuzzer => Relative path to fuzzer from root directory of source
        use_default => Flag indicating whether to fuzz a particular function or
                       start fuzzing from main
        prototype => prototype of function to be fuzzed. Will only be
                     considered if use_default is True
        """
        self.template = open('template.cpp', 'r').read()
        self.path = path
        self.filename = filepath.split('/')[-1]
        self.executable = executable
        self.sourcepath = ''.join(x for x in filepath.split('/')[:-1])
        self.libpath = self.path + '/' + self.sourcepath

        print "[-] Intializing"
        initializeObject = initialize(self.path)
        print "[+] Done"
        chdir(self.sourcepath)
        open('test.cpp', 'w').write(self.template)

        print "[-] Modifying main to runner"
        backupObject = backup(self.filename, initializeObject.getOutput())
        print "[+] Done"

        print "[-] Building shared object"
        libraryObject = makeObject(initializeObject.getOutput(),
                                   self.executable)
        print "[+] Done"

        if use_default is False and prototype is not '':
            print "[-] Creating fuzzer targeting arbitrary function"
            customObject = makeFuzzer(prototype)
            print "[+] Done"

        print "[-] Compiling fuzzer"
        compilefuzzer(libraryObject.getLibFlags(), '../' + fuzzer)
        print "[+] Done"

        print "[-] Starting fuzzing"
        call('./test', env=dict(environ, LD_LIBRARY_PATH=self.libpath))
Ejemplo n.º 22
0
def printer():
    initialize()
    feed_in()

    def thread1():
        """Continuously process the queue of letters."""
        motor['C'].on_for_rotations(50, -2.5)
        carriage_move(0)
        process_queue()
        carriage_move(525)

        def thread1_1():
            motor['C'].on_for_rotations(50, 2.5)

        def thread1_2():
            feed_out()

        fork(thread1_1, thread1_2)

    def thread2():
        """Continuously monitor the touch sensor and convert the Morse code
        sequence into a letter index which gets added to the letter queue.
        """
        read_code()

    def thread3():
        """This will wait for any bluetooth letter messages, and add them to
        the letter queue. This is only relevent if you are using 2 EV3 units to
        have a separate transmitter and receiver.
        """
        while True:
            letter = messaging.wait_update('Letter')
            queue = variables['Queue']
            variables['Queue'] = write_at_index(queue, len(queue), letter)

    fork(thread1, thread2, thread3)
Ejemplo n.º 23
0
 def __init__(self):
     """Init Function for class controls"""
     FORMAT = '%(asctime)-s-%(levelname)s-%(message)s'
     logging.basicConfig(format=FORMAT,
                         filename='hivetests.log',
                         filemode='w',
                         level='INFO')
     logging.getLogger("requests").setLevel(logging.WARNING)
     self.logger = logging.getLogger(__name__)
     self.results = defaultdict(
         lambda: defaultdict(lambda: defaultdict(lambda: [])))
     self.rowsOnQuery = defaultdict(lambda: 'NA')
     self.start_end = defaultdict(lambda: ['NA', 'NA'])
     self.epochdict = defaultdict(lambda: defaultdict(lambda: ['NA', 'NA']))
     self.containers = defaultdict(lambda: defaultdict(lambda: 0))
     self.pstat = partialStats.pstats(self.logger)
     self.initializer = initialize.initialize(self.logger)
Ejemplo n.º 24
0
    def locate_particles(self, observations):
        """ 
        use particle filtering to locate point. The dataframe represent all the
        duty cycle for a participants. Each duty cycle has the strongest signals
        from the routers seen
        """
        # call particle filtering algorithm
        # returns a list of xytuples

        #change to particle filter call
        #limit to initial observation
        obs = observations.loc[observations['record_time'] ==
                               observations.record_time.unique()[0]]
        points_list = pf.particle_filter(observations, init.initialize(obs))

        # reformat to single dataframe
        points = pd.concat(points_list, ignore_index=True)

        #save the list of data frames to a csv file
        points.to_csv('particle.csv', sep='\t')

        return points
Ejemplo n.º 25
0
def main():
    logger = logging.Logger("pipeline_test", level=logging.INFO)

    configuration_dictionary = initialize.initialize()

    # We need to fake out the data passed to PointCloudGenerator. This process does so.
    parser = BluetoothParser()
    gen = PointCloudGenerator(configuration_dictionary)
    real_time_visualizer = RealTimeVisualizer(POINT_CLOUD_FILE_NAME,
                                              PACKAGE_LOCATIONS_FILE_NAME)

    # The parser expects byte data like the serial passes.
    with open(RAW_DATA_PATH, "rb") as f:
        data = f.read()

    for c in data:
        r = parser.add_data(bytes((c, )))
        if r is not None:
            gen.signal(UpdateSignal.NEW_DATA, r)

    gen.mark_finished()

    data_filterer = DataFilterer(configuration_dictionary)

    data_filterer.begin()

    while not data_filterer.finished:
        time.sleep(1)

    mesh_generator = MeshGenerator(configuration_dictionary)
    mesh_generator.begin()

    while not mesh_generator.finished:
        time.sleep(1)

    point_cloud_visualizer = PointCloudVisualizer(UNCERTAINTY_PATH)
    point_cloud_visualizer.begin()

    logger.info("Completed all ATLAS software :)")
Ejemplo n.º 26
0
def execGameCommonInitializeScript(channelName, platformId, appVersion, resVersion, platformType):
    if (os.path.exists(file_operate.getGameCommonScriptPath())):
        
        gameCommonInitScriptBat = file_operate.getGameCommonScriptPath() + "/initialize.bat"
        if (os.path.exists(gameCommonInitScriptBat)):
            cmd = '"%s" "%s" "%s" "%s" "%s"' % (gameCommonInitScriptBat, platformId, channelName, appVersion, resVersion)
            ret = file_operate.execFormatCmd(cmd)
            if ret:
                print "execute initialize.bat error"
                return 1
        gameCommonInitScriptExe = file_operate.getGameCommonScriptPath() + "/initialize.exe"
        if (os.path.exists(gameCommonInitScriptExe)):
            cmd = '"%s" "%s" "%s" "%s" "%s"' % (gameCommonInitScriptExe, platformId, channelName, appVersion, resVersion)
            ret = file_operate.execFormatCmd(cmd)
            if ret:
                print "execute initialize.exe error"
                return 1
        gameCommonInitScriptPyc = file_operate.getGameCommonScriptPath() + "/initialize.pyc"
        if os.path.exists(gameCommonInitScriptPyc):
            sys.path.append(file_operate.getGameCommonScriptPath())
            import initialize
            ret = initialize.initialize(platformId, channelName, platformType, appVersion, resVersion)
Ejemplo n.º 27
0
def main(username, password):
    global isRunning
    global all_processes
    global haveOpened
    global p, all_processes
    global user
    haveOpened = False
    isRunning = True
    AEROSPACE_LOGO = "../assets/logo.png"
    A_LOGO = "../assets/A_logo.jpg"
    webcameraSource = initialize.initialize()
    all_processes = []
    panelHeight = 250
    panelWidth = 250

    # Things that the button does on click
    # Runs a subprocess if there isn't one running
    # Otherwise polls to see if there is a subprocess to kill
    def helloCallBack(widget):
        global haveOpened
        if (haveOpened == False):
            global p, all_processes
            p = Popen([
                "python", "button_popen.py",
                str(webcameraSource), username, password
            ])
            all_processes.append(p)
            haveOpened = True
            widget['background'] = 'red'
            widget['text'] = 'STOP'
            isRunning = True
        else:
            poll = p.poll()
            if (poll == None):
                all_processes.remove(p)
                p.kill()
                widget['background'] = 'green'
                widget['text'] = 'START'
                isRunning = False
            else:
                p = Popen([
                    "python", "button_popen.py",
                    str(webcameraSource), username, password
                ])
                all_processes.append(p)
                widget['background'] = 'red'
                widget['text'] = 'STOP'
                isRunning = True

    # Kills all subprocesses that are running if there are any
    # Also sets isRunning to False so the thread can stop
    def cleanup():
        global all_processes, isRunning
        if len(all_processes) != 0:
            isRunning = False
            for p in all_processes:  # list of your processes
                if isinstance(p, Popen) and p.poll() == None:
                    p.kill()

    # Thread to constantly poll if a process is running or not
    # Reverts the button back to normal if it detects that the process stopped
    def pollProcesses(widget):
        global all_processes, isRunning
        while (isRunning):
            if len(all_processes) != 0:
                for p in all_processes:
                    if isinstance(p, Popen) and p.poll() != None:
                        widget['background'] = 'green'
                        widget['text'] = 'START'
                        isRunning = False
                        # Honestly a horrible idea.
                        # If the array isn't always size 0 or 1 this could lead to some real issues
                        all_processes.remove(p)

    def recalibrate():
        # Note: not tested on linux.
        if (platform.system() != 'Darwin'):
            user = firebase_login.signIntoFirebase(username, password)
            p = Popen(["python", "calibration.py"], stdin=PIPE, stdout=PIPE)
            p.wait()
            calibration_vals = p.returncode
            p.stdout.readline()
            p.stdout.readline()
            firebase_login.updateEyeRatio(username, user,
                                          float(p.stdout.readline()))
            firebase_login.updateMouthRatio(username, user,
                                            float(p.stdout.readline()))
            p.kill()
        else:
            user = firebase_login.signIntoFirebase(username, password)
            calibration_vals = calibration.main()
            firebase_login.updateEyeRatio(username, user, calibration_vals[0])
            firebase_login.updateMouthRatio(username, user,
                                            calibration_vals[1])

    atexit.register(cleanup)

    top = Tkinter.Tk()

    imageText = "AEROSPACE DROWSINESS DETECTOR"
    logo = Image.open(A_LOGO)
    photo = ImageTk.PhotoImage(logo)

    label = Tkinter.Label(top, text=imageText)
    label.pack()

    top.title("Drowsiness Detector")
    #top.resizable(False, False)
    #top.iconbitmap(default="../assets/icon.ico")

    photoPanel = Tkinter.Canvas(top, width=panelWidth, height=panelHeight)
    photoPanel.pack(side='top', fill='both', expand='yes')
    photoPanel.create_image(panelWidth / 2, panelHeight / 2, image=photo)

    B = Tkinter.Button(top,
                       height=2,
                       width=10,
                       background='green',
                       text='START')
    B.config(command=lambda arg=B: helloCallBack(arg))
    B.pack()

    C = Tkinter.Button(top,
                       height=2,
                       width=10,
                       background='green',
                       text='RECALIBRATE')
    C.config(command=recalibrate)
    C.pack()

    t = Thread(target=pollProcesses, args=(B, ))
    t.daemon = True
    t.start()

    top.mainloop()
Ejemplo n.º 28
0
T_min = 0.001
T_max = int(float(sys.argv[9]) * N1 * N2)  # 40
num_T = int(float(sys.argv[10]) * T_max)  # 400
## MC
num_warmup = 1000
num_sampling = 200
num_mc = 100
########################

alpha = np.pi / theta_factor
# build lattice
w_clean, n_clean = buildLattice(N1, N2, alpha, neigb_cutOff)
lattice = np.zeros([N1, N2])

# initialize random
initialize(lattice)
# must use neighbs and weight now
E_int = getEnergy(lattice, n_clean, w_clean, J, H)
P_int = getTotalPolarization(lattice)
print '\n\n    ********   ', E_int, P_int
print lattice
# temps

dT = (T_max - T_min) / (num_T + 0.0)
Temps = np.array([T_min + t * dT for t in range(num_T)])
Temps = list(Temps[::-1])
### for t in Temps ...
#Temp = Temps[0]

E_vs_T = np.zeros([len(Temps), 2])
E2_vs_T = np.zeros([len(Temps), 2])
Ejemplo n.º 29
0
def rnglib_test04 ( ):

#*****************************************************************************80
#
## RNGLIB_TEST04 demonstrates the use of multiple streams.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license. 
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    John Burkardt
#
  from cgn_set import cgn_set
  from init_generator import init_generator
  from initialize import initialize
  from r4_uniform_01 import r4_uniform_01

  print ''
  print 'RNGLIB_TEST04'
  print '  R4_UNIFORM_01 ( ) returns a random real number'
  print '  in [0,1] using the current generator.'
#
#  Initialize the package.
#
  print ''
  print '  INITIALIZE initializes the random number generator.'
  print '  It only needs to be called once before using the package.'

  initialize ( )

  print ''
  print '  Let us call generators #3, #6 and #9.'
#
#  Use three separate generators, 3, 6 and 9.
#  Force them to start at their initial seeds.
#
  g = [ 3, 6, 9 ]
  print ''
  for j in range ( 0, 3 ):
    print '  Initialize generator %d' % ( g[j] )
    cgn_set ( g[j] )
    init_generator ( 0 )
#
#  Call the generators in the order 3, 6, 9.
#
  print ''
  print '   I    R4_UNIFORM_01 ( 3 )  R4_UNIFORM_01 ( 6 )  R4_UNIFORM_01 ( 9 )'
  print ''
  for i in range ( 1, 11 ):
    print '  %2d' % ( i ),
    for j in range ( 0, 3 ):
      cgn_set ( g[j] )
      u = r4_uniform_01 ( )
      print '  %14.6g' % ( u ),
    print ''
#
#  Restart the generators at their initial seeds.
#
  g = [ 6, 9, 3 ]
  print ''
  for j in range ( 0, 3 ):
    print '  Reinitialize generator %d' % ( g[j] )
    cgn_set ( g[j] )
    init_generator ( 0 )
#
#  Call them in a different order, same result.
#
  print ''
  print '   I    R4_UNIFORM_01 ( 6 )  R4_UNIFORM_01 ( 9 )  R4_UNIFORM_01 ( 3 )'
  print ''
  for i in range ( 1, 11 ):
    print '  %2d' % ( i ),
    for j in range ( 0, 3 ):
      cgn_set ( g[j] )
      u = r4_uniform_01 ( )
      print '  %14.6g' % ( u ),
    print ''
Ejemplo n.º 30
0
            continue

        if simulation and now > end_date:
            break

        # happens on the same day as the call to the logic module, but AFTER the call to the logic module
        if not initialized and (now.hour, now.minute) >= (16, 15):
            # important: does not trigger after midnight, to avoid the violations of assumptions made about now_date
            # in relation to the execution of the logicModule, which is set for the next day.
            if not simulation:
                print('')
            print(now.strftime("%Y/%m/%d %H:%M:%S") + ' Initialization')
            now_date = date(year=now.year, month=now.month, day=now.day)
            if not simulation or (now_date - last_initialization_day
                                  ).days >= initialization_frequency:
                initialize.initialize(now_date - datetime.timedelta(days=365),
                                      now_date, simulation)
                last_initialization_day = now_date
            initialized = True

        if not simulation and initialized and not balance_requested and (
                now.hour, now.minute) >= (13, 58):
            if alpaca_enabled:
                alpaca_value = alpaca.sell_all()

            if trading212_enabled:
                print('\nSELL ALL STOCKS NOW!')
                playsound.playsound('gong.wav')

                # balance_eur = 1.0
                # deposits_eur = 0.0
                while True:
Ejemplo n.º 31
0
        'Kyle.tsv',
        'Hinton.tsv',
        'Jake.tsv',
        'Jonathan.tsv',
        'Hannah.tsv',
        'Sahil.tsv',
        'Emily.tsv',
        'Sam.tsv',
        'Alanna.tsv',
        'Griffin.tsv',
        'Xia.tsv',
        'Matt.tsv',
        ]

# 1. Import data
initialize()
module_log = logging.getLogger(__name__)
module_log.info('Importing info')
people = []
for f in files:
    people.append(Person.initFromFile(file_dir + f))

# 2. Make sure days and times are the same and all avail entries valid
module_log.info('Error checking data')
days = people[0].days
times = people[0].times
for i, p in enumerate(people):
    if not p.seats >= 0:
        module_log.error(f'Number of seats must be greater than or equal to zero. See file {i}')
    if sorted(p.days) != sorted(days):
        module_log.error(f'Not all days the same. See file {i}.')
Ejemplo n.º 32
0
Archivo: ATTM.py Proyecto: ua-snap/atm
    def run_attm(self):
        
        """ Program sequence """
        #====================================================
        # Initialization Process
        #====================================================
        print '==================='
        print ' Initializing ATTM'
        print '==================='
        read_control.read_control(self)
        initialize.initialize(self)
        read_layers.read_layers(self)
        model_domain.model_domain(self)
        create_attm_cohort_arrays.create_attm_cohort_arrays(self)
        if self.Simulation_area.lower() == 'barrow':
            initial_cohort_population.barrow_initial_cohort_population(self)
            initial_cohort_check.barrow_initial_cohort_check(self)
            cohort_present.barrow_cohort_present(self)
        elif self.Simulation_area.lower() == 'tanana':
            initial_cohort_population.tanana_initial_cohort_population(self)
            initial_cohort_check.tanana_initial_cohort_check(self)
            cohort_present.tanana_cohort_present(self)

         
        #=======================================
        # READ MET Data & Calculate Degree Days
        #=======================================
        initialize.Met(self)


        #++++++++++++++++++++++++++++++++++++++++++++++
        #  ========================================
        #    INITIALIZE BARROW COHORT PROPERTIES
        #  ========================================
        #++++++++++++++++++++++++++++++++++++++++++++++
        if self.Simulation_area.lower() == 'barrow':
            print '=================================== '
            print ' Initializing Lake & Pond Properties'
            print '===================================='
            initialize.LakePond(self)
            set_lake_pond_depth.set_lake_pond_depth(self)
            set_lake_ice_depth_constant.set_lake_ice_depth_constant(self)
            set_ice_thickness_array.set_ice_thickness_array(self)
            climate_expansion_arrays.set_climate_expansion_arrays(self)
            set_pond_growth_array.set_pond_growth_array(self)

            print '====================================='
            print ' Initializing Terrestrial Properties'
            print '====================================='
            initialize.Terrestrial_Barrow(self)
            read_ice_content.read_ice_content(self)
            read_drainage_efficiency.read_drainage_efficiency(self)
            read_initial_ALD.read_initial_ALD(self)
            set_ALD_constant.set_ALD_constant(self)
            set_ALD_array.set_ALD_array(self)
            set_protective_layer.set_protective_layer(self)
            set_initial_cumulative_probability.set_initial_cumulative_probability(self)
            # Initializing Terrestrial Cohort Properties 
            initialize.Wet_NPG(self)
            initialize.Wet_LCP(self)
            initialize.Wet_CLC(self)
            initialize.Wet_FCP(self)
            initialize.Wet_HCP(self)
            # Other needed information [in the future]
            initial_cohort_age.initial_cohort_age(self)

        elif self.Simulation_area.lower() == 'tanana':
            print '======================================'
            print ' Initializing Terrestrial Properties '
            print '======================================'
            initialize.Terrestrial_Tanana(self)


        print '=================================================='
        print '            Starting the MAIN LOOP '
        print '=================================================='

        initialize.run(self)
        for time in range(0, self.stop):
            if time == 0:
                if self.Simulation_area.lower() == 'barrow':
                    cohorts.initial_barrow(self)
                elif self.Simulation_area.lower() == 'tanana':
                    cohorts.initial_tanana(self)
            print '    at time step: ', time
            
            # ++++++++++++++++++++++++++++++++++++++
            # Check for significant climatic event
            # ++++++++++++++++++++++++++++++++++++++
            check_climate_event.check_climate_event(self)            
           
            # ----------------------------------------------------------
            # Looping over elements
            # ----------------------------------------------------------
            for element in range(0, self.ATTM_nrows * self.ATTM_ncols):
                
                # ----------------------------------------------------
                # Define the total fractional area of cohorts for
                # each element
                # ----------------------------------------------------
                cohort_start = cohort_check.cohort_start(self, element, time)
                
                # ----------------------------------------------------
                # Expand/Infill lake & ponds by prescribed rates
                # ----------------------------------------------------
                lake_pond_expansion.lake_pond_expansion(self, element)
                lake_pond_expansion.pond_infill(self, element, time)
                
                # ----------------------------------------------------------
                # Set active layer depth
                # ---------------------------------------------------------
                active_layer_depth.active_layer_depth(self, time, element)
                
                # ----------------------------------
                # Cycle through terrestrial cohorts
                # ----------------------------------
                check_Wet_NPG.check_Wet_NPG(self, element, time)
                check_Wet_LCP.check_Wet_LCP(self, element, time)
                check_Wet_CLC.check_Wet_CLC(self, element, time)
                check_Wet_FCP.check_Wet_FCP(self, element, time)
                check_Wet_HCP.check_Wet_HCP(self, element, time)

                # ----------------------------------
                # Set pond/lake ice thickness depth
                # ----------------------------------
                ice_thickness.ice_thickness(self, time, element)
                # ------------------------------
                # Cycle through ponds and lakes
                # ------------------------------
                check_Ponds.check_Ponds(self, element, time)
                check_Lakes.check_Lakes(self, element, time)
                 
                # -------------------------------------------------
                # Cohort Fraction Check (mass balance of cohorts)
                # -------------------------------------------------
                cohort_check.cohort_check(self, element, time, cohort_start)

                if time == self.stop-1:
                    if self.Simulation_area.lower() == 'barrow':
                        cohorts.final_barrow(self)
                    elif self.Simulation_area.lower() == 'tanana':
                        cohorts.final_tanana(self)
                    
            # ========================================================================
            # END MAIN LOOP 
            # ========================================================================
            
            # ========================================================================
            # OUTPUT RESULTS (if requested)
            # ========================================================================
            #  - - - - - - - - -
            # Fractional Areas
            #  - - - - - - - - -
            Output_cohorts_by_year.Output_cohorts_by_year(self, time)
            #  - - - - - - - - - - - - -
            # Dominant Fractional Area
            #  - - - - - - - - - - - - - 
            Output_cohorts_by_year.dominant_cohort(self)                 # Terrestrial_Control
            Output_cohorts_by_year.dominant_fractional_plot(self, time)  # Terrestrial_Control

        # =================================
        # OUTPUT ANIMATIONS (if requested)
        # =================================
        # - - - - - - - - - - - - - - -
        # Fractional Area of Cohorts
        # - - - - - - - - - - - - - - - -
        Output_cohorts_by_year.write_Fractions_avi(self)
        Output_cohorts_by_year.write_Dominant_Cohort_avi(self) # Terrestrial_Control

        # -------------------
        # Simulation End Time
        # -------------------
        clock.finish(self)
        
        #===========================
        # Output Simulation Results
        #===========================
        if self.results_onscreen.lower() == 'yes':
            results.on_screen(self)
        if self.archive_simulation.lower() == 'yes':
            results.on_file(self)

        
        # ================
        # Archive Results
        # ================
        if self.archive_simulation.lower() == 'yes':
        #----------------------------------------------------------------------------------------------------------
        # Create the tarfile
        #----------------------------------------------------------------------------------------------------------
            self.archive_file =tarfile.open(self.control['Run_dir']+self.Output_directory+str('/Archive/')+ \
                                            self.archive_time+str('_')+self.simulation_name+".tar.gz", mode='w:gz')
        #----------------------------------------------------------------------------------------------------------
            archive.read_archive(self)
            archive.archive(self)
            
        print '----------------------------------------'
        print '        Simulation Complete             '
        print '----------------------------------------'        
Ejemplo n.º 33
0
Archivo: ATM.py Proyecto: ua-snap/atm
    def run_atm(self):
        
        """ Program sequence """
        #====================================================
        # Initialization Process
        #====================================================
        print '==================='
        print ' Initializing ATM'
        print '==================='
        read_control.read_control(self)
        initialize.initialize(self)
        read_layers.read_layers(self)
        model_domain.model_domain(self)
        create_attm_cohort_arrays.create_attm_cohort_arrays(self)


        #=========================================
        # Initializing Site Specific Information
        #=========================================
        if self.Simulation_area.lower() == 'barrow':
            run_barrow.initialize_barrow(self)
        elif self.Simulation_area.lower() == 'tanana':
            run_tanana.initialize_tanana(self)
         
        #=======================================
        # READ MET Data, Calculate Degree Days,
        # and Calculate Climatic Data needed
        # for ecotype changes.
        #=======================================
        initialize.Met(self)

        #++++++++++++++++++++++++++++++++++++++++++++++
        #  ========================================
        #    INITIALIZE COHORT PROPERTIES
        #  ========================================
        #++++++++++++++++++++++++++++++++++++++++++++++
    	print '======================================'
        print ' Initializing Terrestrial Properties '
        print '======================================'
        if self.Simulation_area.lower() == 'barrow':
            run_barrow.initialize_barrow_cohorts(self)
        elif self.Simulation_area.lower() == 'tanana':
            run_tanana.Terrestrial_Tanana(self)

        print '=================================================='
        print '            Starting the MAIN LOOP '
        print '=================================================='

        initialize.run(self)
        if self.Simulation_area.lower() == 'barrow':
            run_barrow.run_barrow(self, time)
	elif self.Simulation_area.lower() == 'tanana':
	    run_tanana.run_tanana(self, time)

        print '=================================================='
        print '            Finished the MAIN LOOP '
        print '=================================================='


        # -------------------
        # Simulation End Time
        # -------------------
        clock.finish(self)
        
        #===========================
        # Output Simulation Results
        #===========================
        if self.results_onscreen.lower() == 'yes':
            results.on_screen(self)
        if self.archive_simulation.lower() == 'yes':
            results.on_file(self)

        
        # ================
        # Archive Results
        # ================
        if self.archive_simulation.lower() == 'yes':
        #----------------------------------------------------------------------------------------------------------
        # Create the tarfile
        #----------------------------------------------------------------------------------------------------------
            self.archive_file =tarfile.open(self.control['Run_dir']+self.Output_directory+str('/Archive/')+ \
                                            self.archive_time+str('_')+self.simulation_name+".tar.gz", mode='w:gz')
        #----------------------------------------------------------------------------------------------------------
            archive.read_archive(self)
            archive.archive(self)
            
        print '----------------------------------------'
        print '        Simulation Complete             '
        print '----------------------------------------'        
Ejemplo n.º 34
0
def advance_state ( k ):

#*****************************************************************************80
#
## ADVANCE_STATE advances the state of the current generator.
#
#  Discussion:
#
#    This procedure advances the state of the current generator by 2^K
#    values and resets the initial seed to that value.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    Original Pascal version by Pierre L'Ecuyer, Serge Cote.
#    PYTHON version by John Burkardt.
#
#  Reference:
#
#    Pierre LEcuyer, Serge Cote,
#    Implementing a Random Number Package with Splitting Facilities,
#    ACM Transactions on Mathematical Software,
#    Volume 17, Number 1, March 1991, pages 98-111.
#
#  Parameters:
#
#    Input, integer K, indicates that the generator is to be
#    advanced by 2^K values.
#    0 <= K.
#
  from cg_get import cg_get
  from cg_set import cg_set
  from cgn_get import cgn_get
  from initialize import initialize
  from initialized_get import initialized_get
  from multmod import multmod
  from sys import exit

  a1 = 40014
  a2 = 40692
  m1 = 2147483563
  m2 = 2147483399

  if ( k < 0 ):
    print ''
    print 'ADVANCE_STATE - Fatal error!'
    print '  Input exponent K is out of bounds.'
    exit ( 'ADVANCE_STATE - Fatal error!' )
#
#  Check whether the package must be initialized.
#
  if ( not initialized_get ( ) ):
    print ''
    print 'ADVANCE_STATE - Note:'
    print '  Initializing RNGLIB package.'
    initialize ( )
#
#  Get the current generator index.
#
  g = cgn_get ( )

  b1 = a1
  b2 = a2

  for i in range ( 1, k + 1 ):
    b1 = multmod ( b1, b1, m1 )
    b2 = multmod ( b2, b2, m2 )

  [ cg1, cg2 ] = cg_get ( g )
  cg1 = multmod ( b1, cg1, m1 )
  cg2 = multmod ( b2, cg2, m2 )
  cg_set ( g, cg1, cg2 )

  return
Ejemplo n.º 35
0
def i4_uniform ( ):

#*****************************************************************************80
#
## I4_UNIFORM generates a random positive integer.
#
#  Discussion:
#
#    This procedure returns a random integer following a uniform distribution
#    over (1, 2147483562) using the current generator.
#
#    The original name of this function was "random()", but this conflicts
#    with a standard library function name in C.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    Original Pascal version by Pierre L'Ecuyer, Serge Cote.
#    PYTHON version by John Burkardt.
#
#  Reference:
#
#    Pierre LEcuyer, Serge Cote,
#    Implementing a Random Number Package with Splitting Facilities,
#    ACM Transactions on Mathematical Software,
#    Volume 17, Number 1, March 1991, pages 98-111.
#
#  Parameters:
#
#    Output, integer VALUE, the random integer.
#
  from antithetic_get import antithetic_get
  from cg_get import cg_get
  from cg_set import cg_set
  from cgn_get import cgn_get
  from i4_division import i4_division
  from initialize import initialize
  from initialized_get import initialized_get

  a1 = 40014
  a2 = 40692
  m1 = 2147483563
  m2 = 2147483399
#
#  Check whether the package must be initialized.
#
  if ( not initialized_get ( ) ):
    print ''
    print 'I4_UNIFORM - Note:'
    print '  Initializing RNGLIB package.'
    initialize ( )
#
#  Get the current generator index.
#
  g = cgn_get ( )
#
#  Retrieve the seeds for the current generator.
#
  [ cg1, cg2 ] = cg_get ( g )
#
#  Update the seeds.
#
  k = i4_division ( cg1, 53668 )
  cg1 = a1 * ( cg1 - k * 53668 ) - k * 12211

  if ( cg1 < 0 ):
    cg1 = cg1 + m1

  k = i4_division ( cg2, 52774 )
  cg2 = a2 * ( cg2 - k * 52774 ) - k * 3791

  if ( cg2 < 0 ):
    cg2 = cg2 + m2
#
#  Store the updated seeds.
#
  cg_set ( g, cg1, cg2 )
#
#  Construct the random integer from the seeds.
#
  z = cg1 - cg2

  if ( z < 1 ):
    z = z + m1 - 1
#
#  If the generator is in antithetic mode, we must reflect the value.
#
  value = antithetic_get ( )

  if ( value ):
    z = m1 - z

  return z
Ejemplo n.º 36
0
def main():
    #	NewVersion, OldVersion, versionKey = handleVersion(False)
    pwd = os.getcwd()
    wish = 'y'
    #	key = raw_input("Are you sure that new version is not required [y/N]? ")
    initialize()
    whoIsAccountant()
    os.system("clear")
    old_versionKey = False
    ListBottomKey = True  ##### If True, adds the list of drink one more time at the bottom of the list
    while wish == 'y':
        print "Choose a task to be done: [1-10], or press Enter to quit!"
        print "\t 1) Add a member"
        print "\t 2) Remove a member"
        print "\t 3) Count the marks"
        print "\t 4) Get money"
        print "\t 5) Shopping update"
        print "\t 6) Report for individuals"
        print "\t 7) Regular update"
        print "\t 8) Notify the obligors by Email"
        print "\t 9) Update the marks' list"
        print "\t10) Update the accountant info"

        key = raw_input()
        try:
            key = int(key)
        except:
            key = 100
        os.system("clear")
        if key == 1 or key == 2:
            if old_versionKey == False:
                versionKey = True
            else:
                versionKey = False
        else:
            versionKey = False
        if key == 1:
            NewVersion, OldVersion, versionKey = handleVersion(versionKey)
            if versionKey:
                os.chdir(OldVersion + "/csv")
                SystemState('no')
                if OldVersion != NewVersion:
                    shutil.copy(OldVersion + '/csv/PeopleList',
                                NewVersion + '/csv/')
            os.chdir(NewVersion + "/csv")
            AddNewMember()
            SystemState('no')
            CreatePeopleList(ListBottomKey)
            old_versionKey = True
            versionKey = False
        elif key == 2:
            NewVersion, OldVersion, versionKey = handleVersion(versionKey)
            os.chdir(OldVersion + "/csv")
            RemoveMember()
            if OldVersion != NewVersion:
                os.rename(OldVersion + '/csv/PeopleList_tmp',
                          NewVersion + '/csv/PeopleList')
                if versionKey:
                    os.remove(OldVersion + '/csv/PeoplePayment_tmp')
                else:
                    os.rename(OldVersion + '/csv/PeoplePayment_tmp',
                              NewVersion + '/csv/PeoplePayment')
            os.chdir(NewVersion + "/csv")
            CreatePeopleList(ListBottomKey)
            #SystemState('no')
            old_versionKey = True
            versionKey = False
        else:
            NewVersion, OldVersion, versionKey = handleVersion(False)
            #			old_versionKey = versionKey
            os.chdir(NewVersion + "/csv")
            if key == 3:
                CountMarks()
                SystemState('no')
            elif key == 4:
                GetMoney()
            elif key == 5:
                UpdateShoppingList()
            elif key == 6:
                #print "This function is not embedded yet!"
                SendReport()
                #input("test")
            elif key == 7:
                SystemState('yes')
            elif key == 8:
                key_email = raw_input(
                    "Shall people with negative balance be informed via email [y/N]? "
                )
                if key_email == 'y' or key_email == 'Y':
                    ObligorReminder()
            elif key == 9:
                CreatePeopleList(ListBottomKey)
                os.system("clear")
            elif key == 10:
                getAccountantInfo()
                os.system("clear")
            else:
                print('here')
                os.system("clear")

        os.chdir(pwd)
        key_update = key
        os.system("clear")

        key = raw_input("Is there any other task? [y/N]? ")
        os.system("clear")
        if key == 'y' or key == 'Y':
            pass
        else:
            wish = 'no'
            if key_update != 8:
                NewVersion, OldVersion, versionKey = handleVersion(False)
                os.chdir(NewVersion + "/csv")
                SystemState('no')
                os.chdir(pwd)
Ejemplo n.º 37
0
	except Exception as e:
		return f"An Error Occurred reading oas spec: {e}"

OASFILE = getoas()


@app.route('/oaspec', methods=['GET'])
@require_apikey
def getoas():

	return OASFILE
		
    
port = int(os.environ.get('PORT', 8080))
if __name__ == '__main__':

	# comment the next two lines to disable our heartbeat event generator
	# otherwise, we are starting this on a seperate process
	heartbeat_process = Process(target=heartbeat)
	heartbeat_process.start()

	# comment out the next line if you don't want this demo creating a single
	# record per firestore collection
	runfirsttime = init.initialize()

	log.info(f"Some log here") 
	app.run(threaded=True, host='0.0.0.0', port=8080)



Ejemplo n.º 38
0
from initialize import initialize
from regression import regression
from learningCurve import learningCurve
from validationCurve import validationCurve
from polyFeatures import polyFeatures
from featureNormalization import featureNormalization
import plotData
import numpy as np

if __name__=="__main__":

    (X,y,Xcv,ycv,Xtest,ytest) = readData()

    lam = 0 # regularization parameter
    degree = 1 # degree of the polynomial
    theta = initialize(degree)

    # checking code by printing values of cost, derivatives and plotting
    # the linear regression
    # we expect 303.951 for cost
    # then [ -15.30, 598.250 ] for gradient
    print "Cost for initial theta = [1,1]: ", \
        costFunction.computeCost(theta,X,y,lam)
    print "Gradient for initial theta = [1,1]: ", \
        costFunction.computeDeriv(theta,X,y,lam)
    theta = regression(theta,X,y,lam)
    plotData.plotTheta(X,y,theta)

    # Computing the learning curve for linear regression
    (error_train,error_cv) = learningCurve(theta,X,y,Xcv,ycv,lam)
    plotData.plotError(error_train,error_cv)
Ejemplo n.º 39
0
def optimize(seg_env_prototype=None,
             target_prototype=None,
             cluster_env_path=None,
             full_env_path=None,
             N_its=1,
             preloaded_vars=None):
    if preloaded_vars is None:
        env, camera_list, optimization_options, pso_options = initialize(
            seg_env_prototype, target_prototype, cluster_env_path,
            full_env_path)

        env.post_process_environment()
    else:
        # work around to the seg fault issue... load everything in advance, then just pass it in!
        env = preloaded_vars['env']
        camera_list = initialize_camera_list()
        optimization_options = initialize_opt_options()
        pso_options = initialize_pso_options()
        # camera_list = preloaded_vars['camera_list']
        # optimization_options = preloaded_vars['optimization_options']
        # pso_options = preloaded_vars['pso_options']

        env.vedo_mesh = vedo.mesh.Mesh(env.obs_mesh)
        env.opt_options = optimization_options
        env.correct_normals()
        env.n_points = optimization_options.n_points
        env.generate_integration_points()
        env.perch_regions = []
        env.perch_area = 0
        env.set_surface_as_perchable()
        optimization_options.log_performance = True

    # PSO:
    # base dimension for simple 2d problem is 2. scales up depending on selected opt
    camera_particle_dimension = optimization_options.get_particle_size()
    n_cams = len(camera_list)
    N_iterations = pso_options["N_iterations"]
    N_particles = pso_options["N_particles"]

    if pso_options["greedy_search"]:
        particle_dimension = camera_particle_dimension
        num_optimizations = n_cams
    else:
        particle_dimension = n_cams * camera_particle_dimension
        num_optimizations = 1

    bounds = (np.zeros(particle_dimension), np.ones(particle_dimension)
              )  # particle boundaries

    # for velocity update:
    # 'w' is velocity decay aka inertia,
    # 'c1' is "cognitive parameter", e.g. attraction to particle best,
    # 'c2' is "social parameter", e.g. attraction to local/global best
    # 'k' = number of neighbors to consider
    # 'p' = the Minkowski p-norm. 1 for absolute val dist, 2 for norm dist
    options = {
        'c1': pso_options["pso_c1"],
        'c2': pso_options["pso_c2"],
        'w': pso_options["pso_w"],
        'k': pso_options["pso_k"],
        'p': pso_options["pso_p"]
    }

    np.random.seed(round(time.time()))

    # for logging
    pso_keypoints = np.zeros([N_its, num_optimizations, N_iterations + 1, 3],
                             dtype=float)
    optimization_options.search_time = np.zeros(
        [N_its, num_optimizations, N_iterations + 1], dtype=float)
    optimization_options.best_fitness = np.ones(
        [N_its, num_optimizations, N_iterations + 1],
        dtype=float) * env.n_points
    optimization_options.pts_searched = np.zeros(
        [N_its, num_optimizations, N_iterations + 1], dtype=int)

    if pso_options['individual_surface_opt']:
        num_surface_loops = len(env.perch_regions)
        surface_number = range(num_surface_loops)
        N_particles = env.assign_particles_to_surfaces(
            N_particles,
            pso_options["pso_k"],
            neighborhood_search=pso_options["local_search"])
    else:
        num_surface_loops = 1
        surface_number = [-1]
        N_particles = [N_particles]

    # STORE FOR ANALYSIS LATER
    pso_best_fitnesses = np.ones([N_its, num_optimizations]) * env.n_points
    pso_points_searched = np.zeros([N_its, num_optimizations])
    pso_search_time = np.zeros([N_its, num_optimizations])
    pso_best_cameras = []

    # store, for each optimization, time, num particles searched, fitness, standard deviation
    bh = pso_options["boundary_handling"]

    for it in range(N_its):
        print("starting iteration: " + str(it + 1))
        optimization_options.iteration = it
        optimal_cameras = PlacedCameras()

        for i in range(num_optimizations):
            if pso_options["greedy_search"]:
                search_cameras_list = [copy.deepcopy(camera_list[i])]
            else:
                search_cameras_list = camera_list

            best_cost = np.finfo(float).max
            best_pos_surf = -1
            best_pos = np.zeros(particle_dimension)

            for j in range(num_surface_loops):

                optimization_options.data_index = 0
                optimization_options.search_time[it, i, 0] = time.time()

                start_time = datetime.now()

                optimization_options.surface_number = j
                # Future work: investigate velocity clamping...
                if pso_options["local_search"]:
                    optimizer = ps.single.LocalBestPSO(
                        n_particles=N_particles[j],
                        dimensions=particle_dimension,
                        options=options,
                        bounds=bounds,
                        bh_strategy=bh)
                    # velocity_clamp=[-.55, 0.25])
                else:
                    optimizer = ps.single.GlobalBestPSO(
                        n_particles=N_particles[j],
                        dimensions=particle_dimension,
                        options=options,
                        bounds=bounds,
                        bh_strategy=bh)
                    # velocity_clamp=[-.25, 0.25])

                optimization_options.surface_number = surface_number[j]
                # this flag gets reset if the current search has too little variance
                optimization_options.continue_searching = True
                optimization_options.stagnant_loops = 0
                if pso_options["multi_threading"]:
                    # noinspection PyTypeChecker
                    surf_best_cost, surf_best_pos = optimizer.optimize(
                        evaluate_swarm,
                        iters=N_iterations,
                        environment=env,
                        cameras=search_cameras_list,
                        placed_cameras=optimal_cameras,
                        opt_options=optimization_options,
                        n_processes=multiprocessing.cpu_count())
                else:
                    surf_best_cost, surf_best_pos = optimizer.optimize(
                        evaluate_swarm,
                        iters=N_iterations,
                        environment=env,
                        cameras=search_cameras_list,
                        placed_cameras=optimal_cameras,
                        opt_options=optimization_options)

                if surf_best_cost < best_cost:
                    best_cost = copy.deepcopy(surf_best_cost)
                    best_pos = copy.deepcopy(surf_best_pos)
                    if pso_options["individual_surface_opt"]:
                        best_pos_surf = j

            pso_search_time[it,
                            i] = (datetime.now() - start_time).total_seconds()
            pso_best_fitnesses[it, i] = best_cost

            if pso_options["greedy_search"]:
                search_cameras_list_copy = copy.deepcopy(search_cameras_list)
                optimization_options.surface_number = best_pos_surf
                best_cam = convert_particle_to_state(
                    environment=env,
                    particle=best_pos,
                    cameras=search_cameras_list_copy,
                    opt_options=optimization_options)[0]

                # from sim.evaluate import evaluate_arrangement_covariance
                # print("Score should be:" + str(evaluate_arrangement_covariance(env, [best_cam])))

                best_cam_covariance = evaluate_camera_covariance(
                    environment=env, cameras=[best_cam])

                optimal_cameras.append_covariances(
                    copy.deepcopy(best_cam_covariance))
                optimal_cameras.cameras.append(copy.deepcopy(best_cam))

        for i in range(num_optimizations):
            pso_points_searched[it, i] = np.sum(
                optimization_options.pts_searched[it, i, :])

        pso_best_cameras.append(copy.deepcopy(optimal_cameras))

    pso_keypoints[:, :, :, 0] = copy.deepcopy(optimization_options.search_time)
    pso_keypoints[:, :, :,
                  1] = copy.deepcopy(optimization_options.pts_searched)
    pso_keypoints[:, :, :,
                  2] = copy.deepcopy(optimization_options.best_fitness)
    # pso_keypoints[:, :, :, 3] = copy.deepcopy(optimization_options.fitness_deviation)
    for i in range(pso_keypoints.shape[1]):
        pso_keypoints[:, i, :, 0] -= np.reshape(pso_keypoints[:, i, 0, 0],
                                                [-1, 1])  # start time at 0s
    pso_keypoints[:, :, :,
                  1] = np.cumsum(pso_keypoints[:, :, :, 1],
                                 axis=2)  # cumsum of points evaluated...
    pso_keypoints[:, :, :, 2] = np.minimum.accumulate(
        pso_keypoints[:, :, :,
                      2], axis=2)  # cumulative minimum of best fitnesses

    verts = np.zeros([0, 3])
    faces = np.zeros([0, 3])
    face_colors = np.zeros([0, 4])
    for s in env.perch_regions:
        if s.is_valid:
            faces = np.vstack([faces, s.faces + len(verts)])
            verts = np.vstack([verts, s.points])
            fc = np.ones([len(s.faces), 4])
            fc[:, 3] *= 255
            fc[:, :3] *= s.face_colors[0, :]
            # fc = np.concatenate([s.face_colors, 255*np.ones([s.face_colors.shape[0], 1])], axis=1)
            face_colors = np.vstack([face_colors, fc])

    eval_placement = EvaluatePlacement(
        environment=env,
        ground_truth_environment=None,
        placed_cameras=pso_best_cameras[0].cameras,
        optimization_options=optimization_options,
        # sp_linear_density=.2, sp_angular_density=2.5,
        sp_linear_density=.2,
        sp_angular_density=5,
        gs_angular_density=20,
        gs_linear_density=.2,
        n_target=pso_options["N_particles"] * N_iterations)

    eval_placement.pso_best_fitnesses = pso_best_fitnesses
    eval_placement.pso_points_searched = pso_points_searched
    eval_placement.pso_search_time = pso_search_time
    eval_placement.pso_keypoints = pso_keypoints

    print("Done running PSO... Running analysis now.")
    eval_placement.run_analysis(N_its=N_its,
                                pso=True,
                                gridsearch=False,
                                randomsearch=False,
                                bruteforce=False)

    return pso_best_cameras[0].cameras
Ejemplo n.º 40
0
from telegram.ext import MessageHandler
from telegram.ext import Filters
import mimetypes
import subprocess
from datetime import datetime,time,timedelta
import time as tt
import threading

import initialize as init
import receiver as rec
import sender as send

times=[]
sender=''
receiver=''
chat=''
(sender,receiver,chat,times)=init.initialize()

updater = Updater(token=receiver,request_kwargs={'read_timeout': 60, 'connect_timeout': 60})
dispatcher = updater.dispatcher

message_handler=MessageHandler(Filters.all,rec.messagesave2)
dispatcher.add_handler(message_handler)
start_handler = CommandHandler('start',rec.start)
dispatcher.add_handler(start_handler)
senderthreading = threading.Thread(target=send.senderstart,name="senderthread",args=(times,sender,chat))
senderthreading.daemon = True
senderthreading.start()

updater.start_polling()
Ejemplo n.º 41
0

def update_boj(conn, aclist):
    while True:
        aclist = baekjoon.update_aclist(conn, aclist, boj_username)
        time.sleep(5)


def update_snucsepl(conn, boardlist):
    while True:
        boardlist = snucsepl.update_boardlist(conn, boardlist)
        time.sleep(60)


if __name__ == '__main__':
    conn, aclist, boardlist = initialize.initialize()
    conn.send(channel, ':wave:')
    if bool_respond_message:
        t1 = Thread(target=read_msg, args=(conn, ))

    if bool_update_boj:
        t2 = Thread(target=update_boj, args=(conn, aclist))

    if bool_update_pl:
        t3 = Thread(target=update_snucsepl, args=(conn, boardlist))

    if bool_respond_message:
        t1.start()

    if bool_update_boj:
        t2.start()
Ejemplo n.º 42
0
Archivo: oscm.py Proyecto: ravisvi/OSCM
def init(url):
    initialize.initialize()
    subprocess.call("git init", shell=True)
    subprocess.call("git remote add origin %s" % url, shell=True)
Ejemplo n.º 43
0
def main():
    logger = logging.getLogger()
    logger.setLevel(logLevel)
    logging.info('amygActivation: first log message!')
    argParser = argparse.ArgumentParser()
    argParser.add_argument('--config',
                           '-c',
                           default=defaultConfig,
                           type=str,
                           help='experiment config file (.json or .toml)')
    argParser.add_argument('--runs',
                           '-r',
                           default='',
                           type=str,
                           help='Comma separated list of run numbers')
    argParser.add_argument('--scans',
                           '-s',
                           default='',
                           type=str,
                           help='Comma separated list of scan number')
    argParser.add_argument(
        '--deleteTmpNifti',
        '-d',
        default='1',
        type=str,
        help='Set to 0 if rerunning during a single scanning after error')

    args = argParser.parse_args()

    # Initialize the RPC connection to the projectInterface
    # This will give us a dataInterface for retrieving files and
    # a subjectInterface for giving feedback
    clientInterface = ClientInterface()
    dataInterface = clientInterface.dataInterface
    subjInterface = clientInterface.subjInterface
    webInterface = clientInterface.webInterface
    args.dataRemote = dataInterface.isRunningRemote()

    cfg = utils.loadConfigFile(args.config)
    cfg = initialize(cfg, args)

    # DELETE ALL FILES IF FLAGGED (DEFAULT) #
    if args.deleteTmpNifti == '1':
        deleteTmpFiles(cfg, args)
    else:
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        print('NOT DELETING NIFTIS IN tmp/convertedNiftis')
        print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')

    createTmpFolder(cfg, args)

    #### MAIN PROCESSING ###
    nRuns = len(cfg.runNum)
    for runIndex in np.arange(nRuns):
        # Steps that we have to do:
        # 1. load run regressor X - ** make run regressor that has TRs -
        # 2. find the happy face trials (happy) X
        # 3. find the rest TRs right before each one  X
        # At every TR --> register to MNI, mask, etc
        # 4. zscore previous rest data (convert + register like before)
        # 5. calculate percent signal change over ROI
        # 6. save as a text file (Every TR-- display can smooth it)

        runNum = cfg.runNum[
            runIndex]  # this will be 1-based now!! it will be the actual run number in case it's out of order
        runId = makeRunHeader(cfg, args, runIndex)
        run = cfg.runNum[runIndex]
        # create run folder
        runFolder = createRunFolder(cfg, args, runNum)
        scanNum = cfg.scanNum[runIndex]
        regressor = makeRunReg(cfg,
                               args,
                               dataInterface,
                               runNum,
                               runFolder,
                               saveMat=1)

        # intialize data stream
        dicomScanNamePattern = utils.stringPartialFormat(
            cfg.dicomNamePattern, 'SCAN', scanNum)
        streamId = dataInterface.initScannerStream(cfg.dicomDir,
                                                   dicomScanNamePattern,
                                                   cfg.minExpectedDicomSize)

        happy_TRs = findConditionTR(regressor, int(cfg.HAPPY))
        happy_TRs_shifted = happy_TRs + cfg.nTR_shift
        happy_TRs_shifted_filenum = happy_TRs_shifted + cfg.nTR_skip  # to account for first 10 files that we're skipping
        happy_blocks = list(split_tol(happy_TRs_shifted, 1))
        TR_per_block = cfg.nTR_block

        fixation_TRs = findConditionTR(regressor, int(cfg.REST))
        fixation_TRs_shifted = fixation_TRs + cfg.nTR_shift
        fixation_blocks = list(split_tol(fixation_TRs_shifted, 1))

        runData = StructDict()
        runData.all_data = np.zeros(
            (cfg.nVox[cfg.useMask], cfg.nTR_run - cfg.nTR_skip))
        runData.percent_change = np.zeros((cfg.nTR_run - cfg.nTR_skip, ))
        runData.percent_change[:] = np.nan
        runData.badVoxels = np.array([])

        TRindex = 0
        for TRFilenum in np.arange(cfg.nTR_skip + 1,
                                   cfg.nTR_run + 1):  # iterate through all TRs
            if TRFilenum == cfg.nTR_skip + 1:  # wait until run starts
                timeout_file = 180
            else:
                timeout_file = 5
            A = time.time()
            dicomFilename = dicomScanNamePattern.format(TR=TRFilenum)
            print(f'Get Dicom: {dicomFilename}')
            dicomData = dataInterface.getImageData(streamId, int(TRFilenum),
                                                   timeout_file)
            if dicomData is None:
                print('Error: getImageData returned None')
                return
            full_nifti_name = convertToNifti(cfg, args, TRFilenum, scanNum,
                                             dicomData)
            print(full_nifti_name)
            print(cfg.MASK_transformed[cfg.useMask])
            maskedData = apply_mask(full_nifti_name,
                                    cfg.MASK_transformed[cfg.useMask])
            runData.all_data[:, TRindex] = maskedData
            B = time.time()
            print('read to mask time: {:5f}'.format(B - A))

            if TRindex in happy_TRs_shifted:  # we're at a happy block
                # now take previous fixation block for z scoring
                this_block = [
                    b for b in np.arange(4) if TRindex in happy_blocks[b]
                ][0]
                fixation_this_block = fixation_blocks[this_block]
                avg_activity, runData = getAvgSignal(fixation_this_block,
                                                     runData, TRindex, cfg)
                runData.percent_change[TRindex] = calculatePercentChange(
                    avg_activity, runData.all_data[:, TRindex])

                text_to_save = '{0:05f}'.format(
                    runData.percent_change[TRindex])
                file_name_to_save = getOutputFilename(
                    run,
                    TRFilenum)  # save as the actual file number, not index
                # now we want to always send this back to the local computer running the display
                full_file_name_to_save = os.path.join(
                    cfg.local.subject_full_day_path, runId, file_name_to_save)
                # Send classification result back to the console computer
                try:
                    dataInterface.putFile(full_file_name_to_save, text_to_save)
                except Exception as err:
                    print('Error putFile: ' + str(err))
                    return
                # JUST TO PLOT ON WEB SERVER
                subjInterface.setResult(run, int(TRFilenum),
                                        float(runData.percent_change[TRindex]))
                webInterface.plotDataPoint(
                    run, int(TRFilenum),
                    float(runData.percent_change[TRindex]))
            TRheader = makeTRHeader(cfg, runIndex, TRFilenum, TRindex,
                                    runData.percent_change[TRindex])
            TRindex += 1

        # SAVE OVER RUN
        runData.scanNum = scanNum  # save scanning number
        runData.subjectName = cfg.subjectName
        runData.dicomDir = cfg.dicomDir
        run_filename = getRunFilename(cfg.sessionId, run)
        full_run_filename_to_save = os.path.join(runFolder, run_filename)
        sio.savemat(full_run_filename_to_save, runData, appendmat=False)

    sys.exit(0)
Ejemplo n.º 44
0
def rnglib_test03 ( ):

#*****************************************************************************80
#
## RNGLIB_TEST03 demonstrates how the seed can be reset to its initial or last value.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license. 
#
#  Modified:
#
#    27 May 2013
#
#  Author:
#
#    John Burkardt
#
  from cgn_set import cgn_set
  from init_generator import init_generator
  from initialize import initialize
  from r4_uniform_01 import r4_uniform_01

  print ''
  print 'RNGLIB_TEST03'
  print '  R4_UNIFORM_01 ( ) returns a random real number'
  print '  in [0,1] using the current generator.'
#
#  Initialize the package.
#
  print ''
  print '  INITIALIZE initializes the random number generator.'
  print '  It only needs to be called once before using the package.'

  initialize ( )

  print ''
  print '  INIT_GENERATOR can reset the seed to the initial value,'
  print '  the last (previous) value, or a new seed.'
#
#  Set the current generator index to 17.
#
  g = 17
  cgn_set ( g )
  print ''
  print '  Current generator index = %d' % ( g )
#
#  Force the current generator to begin at its initial seed.
#
  print ''
  print '  INIT_GENERATOR ( 0 ) starts at the initial seed.'

  init_generator ( 0 )

  print ''
  print '   I    R4_UNIFORM_01 ( )'
  print ''
  for i in range ( 1, 10 ):
    u = r4_uniform_01 ( )
    print '  %2d  %14.6g' % ( i, u )

  print ''
  print '  Calling INIT_GENERATOR ( 0 ) again restarts'
  print '  at the initial seed.'

  init_generator ( 0 )

  print ''
  print '   I    R4_UNIFORM_01 ( )'
  print ''
  for i in range ( 1, 10 ):
    u = r4_uniform_01 ( )
    print '  %2d  %14.6g' % ( i, u )

  print ''
  print '  Calling INIT_GENERATOR ( 2 ) restarts'
  print '  at a new "far ahead" seed.'

  init_generator ( 2 )

  print ''
  print '   I    R4_UNIFORM_01 ( )'
  print ''
  for i in range ( 1, 10 ):
    u = r4_uniform_01 ( )
    print '  %2d  %14.6g' % ( i, u )

  print ''
  print '  Calling INIT_GENERATOR ( 1 ) restarts'
  print '  at the last seed (in this case, the "far ahead"'
  print '  seed specified on the previous call.)'

  print ''
  print '   I    R4_UNIFORM_01 ( )'
  print ''
  for i in range ( 1, 11 ):
    u = r4_uniform_01 ( )
    print '  %2d  %14.6g' % ( i, u )
    if ( ( i % 3 ) == 0 ):
      init_generator ( 1 )
      print '  (Reset to last seed)'