Ejemplo n.º 1
0
 def readConfig(self, configName, args):
     _cfgPath = os.path.join(
         util.getEnvPath("THIS_DIR"), "cfg", configName + ".ini")
     if not os.path.exists(_cfgPath):
         raise ValueError("Config with name %s not found in %r" % (
             configName, _cfgPath))
     return util.readConfigFile(_cfgPath, args)
Ejemplo n.º 2
0
 def __init__(self, allImageObjects, destDirectory):
     self.allImageObjects = allImageObjects
     self.destDirectory = destDirectory
     config = readConfigFile()
     general = config["GENERAL"]
     self.allowedAspectDiff = general.getfloat("ALLOWED_ASPECT_DIFF")
     self.selectedImages = []
     self.combineId = None
Ejemplo n.º 3
0
    def __init__(self, args):
        self.args = args
        config = readConfigFile()
        general = config["GENERAL"]
        self.nsfw_allowed = general.getboolean("NSFW_ALLOWED")
        self.subreddits = general["SUBREDDITS"]

        self.incorrect_aspect = []
        self.correct_aspect = []

        self.apiObject = praw.Reddit(client_id=os.environ["CLIENT_ID"],
                                     client_secret=os.environ["SECRET"],
                                     user_agent=os.environ["USER_AGENT"])
Ejemplo n.º 4
0
        
        #util.raiseNotDefined()


############################################
    #TESTING
###########################################

# run with '-h' for 'usage'
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-p", choices=['NQueens', 'sudoku'], default='NQueens', help="type of problem")
parser.add_argument("-n", type=int, default=4, help="size of problem")
parser.add_argument("-t", type=int, default=10000, help="number of iterations")
parser.add_argument("-i", default='test', help="file containing the initial input configuration for sudoku")
args = parser.parse_args()

if args.p == "NQueens":
    prob = [NQueensProblem(args.n)]    # no solution for < 4
    print 'NQueens: n =', args.n
elif args.p == "sudoku":
    predefValues = util.readConfigFile(args.i)
    print len(predefValues), 'sudoku(s)'
    prob = [sudoku(N=args.n, predefinedValues=val) for val in predefValues]
    print 'sudoku: n =', args.n

#state = prob.getStartState()

for p in prob:
    print solveAgent.minConflict(p, args.t)
Ejemplo n.º 5
0
def run(args, logger, plotter):
  # Read config file for simulation parameters.
  #
  cfg = readConfigFile(logger, args.i)
  xtra_header_keys = {} # dict of extra keys and values for FITS header
  st = time.time()
  
  logger.debug(" Beginning simulation")
  
  # Build Zemax spectrograph model
  #
  zspec = zSpectrograph(cfg['SIM_COLLIMATOR_ZMX_FILE'], 
    cfg['SIM_CAMERA_ZMX_FILE'])

  # Build the instrument using the instrument_builder package.
  #
  # Although we construct the components from the configuration files, we 
  # override some attributes to both ensure consistency and accept some 
  # limitations of the current version.
  #
  # -> Assign camera/collimator EFFL to directly match the Zemax models.
  # -> Set the preoptics WFNO such that a spatial resolution element spans 
  #    [IFU_SLICES_PER_RESEL] slices.
  # -> Set the preoptics anamorphic magnification to 1
  # 
  instrument = SWIFT_like(cfg['PREOPTICS_CFG_NAME'], 
    cfg['IFU_CFG_NAME'], 
    cfg['SPECTROGRAPH_CFG_NAME'], 
    cfg['DETECTOR_CFG_NAME'], 
    config_dir=cfg['SIM_INSTRUMENT_CONFIGS_DIR_PATH'],
    logger=logger)

  zspec_attr = zspec.getSystemAttr(cfg['PUPIL_REFERENCE_WAVELENGTH'])

  instrument.spectrograph.cfg['camera_EFFL'] = zspec_attr['camera_EFFL']
  instrument.spectrograph.cfg['collimator_EFFL'] = zspec_attr['collimator_EFFL']

  instrument.preoptics.cfg['magnification_across_slices'] = \
    instrument.preoptics.cfg['magnification_along_slices']

  # following assumes diffraction-limited reimaging performance
  instrument.preoptics.cfg['WFNO'] = cfg['IFU_SLICES_PER_RESEL'] * \
    instrument.ifu.cfg['slice_width_physical'] / \
    cfg['PUPIL_REFERENCE_WAVELENGTH']

  instrument.assemble()

  # Get wavelength range as decimal.
  #
  waves = np.arange(cfg['SIM_WAVELENGTH_START'],
    Decimal(cfg['SIM_WAVELENGTH_END'] + \
    cfg['SIM_WAVELENGTH_INTERVAL']),
    Decimal(cfg['SIM_WAVELENGTH_INTERVAL']), dtype=Decimal)

  # Determine the smallest pupil size (D_pupil) that corresponds to Nyquist 
  # sampling at the detector given a camera focal length, f_cam, and some 
  # reference wavelength, lambda. 
  #
  # As we want to be AT LEAST Nyquist sampling at all wavelengths, we really
  # want to ensure that the system is Nyquist sampling at the shortest 
  # wavelength. Doing so means that longer wavelengths will be oversampled. 
  # The wavelength at which the pupil is constructed for can be adjusted in 
  # the configuration file as [pupil.reference_wavelength].
  # 
  # We get [D_pupil], the pupil size for a single slice, by equating the spatial
  # size of 2 detector pixels (D_p) with the spatial size of one resolution 
  # element, i.e.
  # 
  #                  2 x D_p = lambda*f_cam / D_pupil
  # 
  pupil_physical_diameter = (cfg['PUPIL_REFERENCE_WAVELENGTH'] * \
    instrument.camera_EFFL)/(2*instrument.detector_pixel_pitch)
  pupil_physical_radius = (pupil_physical_diameter/2)
  
  xtra_header_keys['EPD'] = (pupil_physical_diameter*1e3,
    "physical entrance pupil diameter (mm)")
  
  # Now find parameters with which we will rescale the image.
  #
  # As the angular size (and thus spatial size) of the resolution element is 
  # dependent on lambda, we need to define a reference system through which we 
  # can resample each wavelength. The wavelength this is done for is defined 
  # in the configuration file as [pupil.resample_to_wavelength]. 
  #
  # To do this, we first stablish the spatial pixel scale (m/px) for the 
  # reference wavelength. The latter is then used to determine the scale factor 
  # which needs to be applied to the wavelength currently being considered. To
  # avoid extrapolation, this reference wavelength should be blueward of the 
  # smallest wavelength to be considered.
  #  
  # All the information required to rescale is held in the [resampling_im] 
  # instance.
  #
  logger.debug(" Ascertaining parameters to resample to " + \
    str(cfg['PUPIL_RESAMPLE_TO_WAVELENGTH']*Decimal('1e9')) + "nm")
  
  resampling_pupil = pupil_circular(logger, cfg['PUPIL_SAMPLING'],
    cfg['PUPIL_GAMMA'], pupil_physical_radius, verbose=True) 

  preoptics_reimager = reimager(instrument.preoptics_WFNO)

  resampling_im = resampling_pupil.toConjugateImage(
    cfg['PUPIL_RESAMPLE_TO_WAVELENGTH'], 
    preoptics_reimager, verbose=True)
  
  # Initialise datacube and run simulations for each wavelength.
  # 
  # The result from a simulation is an image instance which we can append 
  # to the datacube.
  #
  dcube = cube(logger)
  s = sim(logger, plotter, resampling_im, resampling_pupil, len(waves), 
          preoptics_reimager, zspec, cfg, instrument)  
  
  for idx, w in enumerate(waves):
    logger.info(" !!! Processing for a wavelength of " + str(float(w)*1e9) + 
                "nm...") 
    
    this_st = time.time()
    dcube.append(s.run(w, verbose=args.v))
    this_duration = time.time()-this_st
    
    if idx>0:
      logger.debug(" Last wavelength iteration took " + str(int(this_duration)) 
                   + "s, expected time to completion is " + 
                   str(int(((len(waves)-(idx+1))*this_duration))) + "s.")
    
  # Make and view output.
  #
  # Note that pyds9 interaction only works with systems with the XPA protocol 
  # installed, and i've yet to find a way to get this working on a Windows box.
  # 
  dcube.write(args, cfg, xtra_header_keys)
  if args.d:
    import pyds9
    d = pyds9.DS9()
    d.set("file " + args.f)
    d.set('cmap heat')
    d.set('scale log')
    d.set('zoom 4')
  
  duration = time.time()-st
  logger.debug(" This simulation completed in " + str(sf(duration, 4)) + "s.")