Ejemplo n.º 1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('geofile', nargs='+')
    parser.add_argument(
        '-o',
        '--outfile',
        help='Save  all  the input GEO files to a single CTL file.')
    parser.add_argument('--no-offset', action="store_true")
    parser.add_argument('-v',
                        '--verbose',
                        action="count",
                        dest="verbosity",
                        default=0,
                        help='verbosity level')
    args = parser.parse_args()

    if args.verbosity > 0:
        print(args)

    if args.outfile:
        ctlfile = args.outfile
        print('{} -> {}'.format(args.geofile, ctlfile))
        sim = bfdtd.readBristolFDTD(*args.geofile, verbosity=args.verbosity)
        sim.writeCtlFile(ctlfile, no_offset=args.no_offset)
    else:
        for geofile in args.geofile:
            #ctlfile = os.path.splitext(args.geofile)[0] + '.ctl'
            ctlfile = geofile + '.ctl'
            print('{} -> {}'.format(geofile, ctlfile))
            sim = bfdtd.readBristolFDTD(geofile, verbosity=args.verbosity)
            sim.writeCtlFile(ctlfile, no_offset=args.no_offset)

    return 0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('infile', nargs='+')
  parser.add_argument('-o', '--outdir',required=True)
  parser.add_argument('-b', '--basename',required=True)
  parser.add_argument('-t', '--target', default='defect')
  eps_group = parser.add_mutually_exclusive_group(required=True)
  eps_group.add_argument('-e', '--epsilon', type=float)
  eps_group.add_argument('-n', '--index', type=float)
  
  args = parser.parse_args()
  
  print(args)
  
  # read input
  sim = bfdtd.readBristolFDTD(*args.infile, verbosity=0)
  
  # change index of targets
  obj_list = sim.getGeometryObjectsByName(args.target)
  for obj in obj_list:
    if args.index:
      obj.setRefractiveIndex(args.index)
    else:
      obj.setRelativePermittivity(args.epsilon)

  # create epsilon run of new sim
  sim.setIterations(1)
  sim.setFileBaseName(args.basename)
  sim.setWallTime(120)
  sim.writeTorqueJobDirectory(args.outdir)
  
  return 0
def main():
    parser = argparse.ArgumentParser()
    #parser.add_argument('-o', '--outfile', default='snapshot_overview.txt')
    parser.add_argument('infile')
    parser.add_argument('-v',
                        '--verbose',
                        action="count",
                        dest="verbosity",
                        default=0,
                        help='verbosity level')
    args = parser.parse_args()
    #print(args)

    sim = bfdtd.readBristolFDTD(args.infile, verbosity=args.verbosity)
    N = sim.getLatestFrequencySnapTimeNumber()
    (fsnapshot_file_names, tsnapshot_file_names, esnapshot_file_names,
     probe_file_names) = sim.getOutputFileNames(fsnap_time_number=N)
    freq_list = sim.getSnapshotFrequencySet()
    Nfreqs = len(freq_list)

    (ex, ey, ez) = esnapshot_file_names
    (ex, ext) = os.path.splitext(ex)
    (ey, ext) = os.path.splitext(ey)
    (ez, ext) = os.path.splitext(ez)

    for (idx, freq) in enumerate(freq_list):
        fx = fsnapshot_file_names[0 + idx]
        fy = fsnapshot_file_names[0 + idx + Nfreqs]
        fz = fsnapshot_file_names[0 + idx + 2 * Nfreqs]
        (fx, ext) = os.path.splitext(fx)
        (fy, ext) = os.path.splitext(fy)
        (fz, ext) = os.path.splitext(fz)
        print('{} {} {} {} {} {} {}'.format(fx, ex, fy, ey, fz, ez, freq))

    return 0
Ejemplo n.º 4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', nargs='+')
    args = parser.parse_args()

    sim = bfdtd.readBristolFDTD(*args.infile, verbosity=0)

    defect_list = sim.getGeometryObjectsByName('defect')
    if len(defect_list) != 1:
        raise Exception(
            'invalid number of defects found!: len(defect_list)={}'.format(
                len(defect_list)))
    defect_radius = defect_list[0].getOuterRadius()
    defect_permittivity = defect_list[0].getRelativePermittivity()

    freq_set = sim.getSnapshotFrequencySet()
    if len(freq_set) != 1:
        raise Exception(
            'invalid number of frequencies found!: len(freq_set)={}'.format(
                len(freq_set)))
    freq = freq_set.pop()

    print('{};{};{}'.format(defect_permittivity, defect_radius, freq))

    return 0
Ejemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', nargs='+')
    args = parser.parse_args()

    sim = bfdtd.readBristolFDTD(*args.infile, verbosity=0)
    defect_list = sim.getGeometryObjectsByName('defect')
    if defect_list:
        print(defect_list[0].getOuterRadius())
    else:
        print(0)

    return 0
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('infile', help='source .inp file containing original mesh')
  parser.add_argument('outfile', help='destination .inp file to write containing new mesh')
  parser.add_argument('-Nx', type=int, default=1, help='factor by which to increase the resolution in the X direction')
  parser.add_argument('-Ny', type=int, default=1, help='factor by which to increase the resolution in the Y direction')
  parser.add_argument('-Nz', type=int, default=1, help='factor by which to increase the resolution in the Z direction')
  parser.add_argument('-v', '--verbose', action="count", dest="verbosity", default=0, help='verbosity level')
  args = parser.parse_args()
  
  # read input
  sim = bfdtd.readBristolFDTD(args.infile, verbosity=args.verbosity)
  mesh = bfdtd.increaseResolution3D(sim.getMesh(), args.Nx, args.Ny, args.Nz)
  with open(args.outfile, 'w') as fid:
    mesh.writeMesh(fid)
  
  return 0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', nargs='+')
    parser.add_argument('-v',
                        '--verbose',
                        action="count",
                        dest="verbosity",
                        default=0,
                        help='verbosity level')
    parser.add_argument('-c',
                        '--continue-on-error',
                        action="store_true",
                        help='continue on errors')
    args = parser.parse_args()

    if args.verbosity > 0:
        print(args)

    ok = []
    fail = []

    for infile in args.infile:
        sim = bfdtd.readBristolFDTD(infile, verbosity=args.verbosity)
        sim.setVerbosity(args.verbosity)
        #sim.setSafetyChecks(False)
        try:
            sim.checkSimulation()
        except Exception as inst:
            print('{} : FAIL -> {}'.format(infile, inst.args))
            fail.append(infile)
            if not args.continue_on_error:
                raise
        except:
            print('Unexpected exception!:')
            raise
        else:
            print('{} : OK'.format(infile))
            ok.append(infile)

    print('OK: {}/{}'.format(len(ok), len(args.infile)))
    print('FAIL: {}/{}'.format(len(fail), len(args.infile)))
    print('N(total)-N(ok)-N(fail) = {}'.format(
        len(args.infile) - len(ok) - len(fail)))
    return 0
Ejemplo n.º 8
0
def analyzeInput(fileName, verbosity=0):

    simulation_info = getSimulationInfoDictionary()

    infile = os.path.splitext(fileName)[0] + '.in'
    FDTDobj = bfdtd.readBristolFDTD(infile, verbosity=verbosity)

    outfile = os.path.splitext(fileName)[0] + '.out'
    timelog = os.path.join(os.path.dirname(fileName),
                           'time{}.txt'.format(FDTDobj.getIdString()))

    ok_timelog = True
    try:
        (delta_N, delta_datetime) = analyzeTimeLog(timelog,
                                                   verbosity=verbosity)
    except:
        ok_timelog = False
        delta_N = 0
        delta_datetime = datetime.timedelta()

    ok_outfile = True
    try:
        done = analyzeOutput(outfile, verbosity=verbosity)
    except:
        ok_outfile = False
        done = False

    if done:
        delta_N = FDTDobj.getIterations()

    Ncells = FDTDobj.getNcells()

    #T = delta_datetime.total_seconds()
    if delta_N == 0:
        time_per_iteration_per_cell = datetime.timedelta()
        time_per_iteration = datetime.timedelta()
    else:
        time_per_iteration_per_cell = delta_datetime / (Ncells * delta_N)
        time_per_iteration = delta_datetime / delta_N

    progress = delta_N / FDTDobj.getIterations()
    iterations_left = FDTDobj.getIterations() - delta_N
    time_left = iterations_left * time_per_iteration
    ETA = datetime.datetime.now() + time_left

    #strfdelta(time_left
    #print('time_left : {} seconds = {} minutes = {} hours = {} days'.format(time_left)
    if verbosity > 0:
        print('infile = {}'.format(infile))
        print('outfile = {}'.format(outfile))
        print('timelog = {}'.format(timelog))
        print('Ncells = {}'.format(Ncells))
        print(
            'time/iteration/cell : {} = {} seconds/iteration/cell = {} days/iteration/cell'
            .format(
                time_per_iteration_per_cell,
                time_per_iteration_per_cell.total_seconds(),
                time_per_iteration_per_cell.total_seconds() / (60 * 60 * 24)))
        print('time/iteration : {} = {} seconds/iteration = {} days/iteration'.
              format(time_per_iteration, time_per_iteration.total_seconds(),
                     time_per_iteration.total_seconds() / (60 * 60 * 24)))
        print('progress : {:%}'.format(progress))
        print('time_left : {}'.format(time_left))
        print('estimated end time : {}'.format(ETA))
        print('done : {}'.format(done))

    simulation_info['infile'] = infile
    simulation_info['outfile'] = outfile
    simulation_info['timelog'] = timelog
    simulation_info['iterations_current'] = delta_N
    simulation_info['iterations_total'] = FDTDobj.getIterations()
    simulation_info['iterations_left'] = iterations_left
    simulation_info['Ncells'] = Ncells
    simulation_info['progress'] = progress
    simulation_info['time_elapsed'] = delta_datetime
    simulation_info[
        'time_per_iteration_per_cell'] = time_per_iteration_per_cell
    simulation_info['time_per_iteration'] = time_per_iteration
    simulation_info['time_left'] = time_left
    simulation_info['estimated_end_time'] = ETA
    simulation_info['status'] = done

    return simulation_info
Ejemplo n.º 9
0
def resonance_run(args):
    ''' Copy src to dst with added frequency snapshots from freqListFile '''
    src = os.path.abspath(args.src).rstrip(os.sep)
    dst = os.path.abspath(args.dst).rstrip(os.sep)
    if os.path.isdir(src):
        print(src + ' is a directory')
        sim = bfdtd.readBristolFDTD(src + os.sep + os.path.basename(src) +
                                    '.in')
        if not args.fileBaseName:
            fileBaseName = os.path.basename(src)
    else:
        print(src + ' is not a directory')
        sim = bfdtd.readBristolFDTD(src)
        if not args.fileBaseName:
            fileBaseName = os.path.splitext(os.path.basename(src))[0]

    freqs = getFrequencies(args.freqListFile)

    print('---')
    print('Frequencies:')
    for f in freqs:
        print(f)
    print('---')

    # get src snapshot lists
    (all_time_snapshots, time_snapshots, epsilon_snapshots,
     mode_filtered_probes) = sim.getAllTimeSnapshots()
    fsnap_list = sim.getFrequencySnapshots()

    new_snapshot_list = []

    if args.frequency_to_energy:
        for fsnap in fsnap_list:
            energy_snapshot = bfdtd.EnergySnapshot()
            energy_snapshot.setFromSnapshot(fsnap)
            energy_snapshot.setFrequencies(freqs)
            new_snapshot_list.append(energy_snapshot)

    if args.new_central:
        box = bfdtd.SnapshotBoxXYZ()
        exc = sim.getExcitations()[0]
        if args.intersection_at_P1:
            (P1, P2) = exc.getExtension()
            print('P1 = {}'.format(P1))
            box.setIntersectionPoint(P1)
        else:
            box.setIntersectionPoint(exc.getCentro())
        energy_snapshot = bfdtd.EnergySnapshot()
        energy_snapshot.setFrequencies(freqs)
        box.setBaseSnapshot(energy_snapshot)
        new_snapshot_list.append(box)

    print(new_snapshot_list)
    print(len(new_snapshot_list))

    if args.clearAllSnapshots:
        sim.clearAllSnapshots()
    if args.clearEpsilonSnapshots:
        sim.clearEpsilonSnapshots()
    if args.clearFrequencySnapshots:
        sim.clearFrequencySnapshots()
    if args.clearModeFilteredProbes:
        sim.clearModeFilteredProbes()
    if args.clearTimeSnapshots:
        sim.clearTimeSnapshots()
    if args.clearProbes:
        sim.clearProbes()
    if args.clearGeometry:
        sim.clearGeometry()

    if args.iterations:
        sim.setIterations(args.iterations)

    sim.appendSnapshot(new_snapshot_list)

    exc = sim.getExcitations()[0]
    if args.source_frequency_range:
        exc.setFrequencyRange(*args.source_frequency_range)
    elif args.source_wavelength_range:
        exc.setWavelengthRange(*args.source_wavelength_range)
    elif args.source_frequency_range_from_DBR:
        wavelength, nLow, nHigh = args.source_frequency_range_from_DBR
        obj = geometries.DBR.DBR(wavelength, nLow, nHigh)
        fmin, fmax = obj.getFrequencyRange()
        exc.setFrequencyRange(fmin, fmax)
    elif args.source_frequency_range_max:
        lambda0 = args.source_frequency_range_max
        f0 = get_c0() / lambda0
        delta_f = f0 / 4
        fmin = f0 - delta_f / 2
        fmax = f0 + delta_f / 2
        exc.setFrequencyRange(fmin, fmax)

    print('FrequencyRange = {}'.format(exc.getFrequencyRange()))
    print('WavelengthRange = {}'.format(exc.getWavelengthRange()))
    print('exc.getPeriod() = {}'.format(exc.getPeriod()))
    print('exc.getTimeConstant() = {}'.format(exc.getTimeConstant()))
    print('exc.getPeriod()/exc.getTimeConstant() = {}'.format(
        exc.getPeriod() / exc.getTimeConstant()))

    exc.setStartTime(0)

    sim.printInfo()

    sim.setFileBaseName(fileBaseName)
    sim.setWallTime(args.walltime)
    sim.setAutosetNFrequencySnapshots(10)

    if args.run_source:
        sim.setSizeAndResolution([1, 1, 1], [32, 32, 32])
        sim.getBoundaries().setBoundaryConditionsNormal()
        sim.clearAllSnapshots()
        sim.clearProbes()
        sim.clearGeometry()

        exc = sim.getExcitations()[0]
        exc.setLocation(sim.getCentro())
        exc.setSize([0, 0, 0])

        p = sim.appendProbe(bfdtd.Probe())
        p.setStep(1)
        p.setLocation(exc.getLocation())

        sim.setSimulationTime(sim.getExcitationEndTimeMax())

    sim.writeTorqueJobDirectory(dst)
    #sim.writeAll(dst, fileBaseName)
    #sim.writeShellScript(os.path.join(dst, fileBaseName+'.sh'))

    print(sim.getSnapshots())
    for s in sim.getSnapshots():
        print(s.getName())
Ejemplo n.º 10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile')
    parser.add_argument('-v',
                        '--verbose',
                        action="count",
                        dest="verbosity",
                        default=0,
                        help='general verbosity level')
    parser.add_argument('-t',
                        '--t-range',
                        nargs=2,
                        metavar=('TMIN', 'TMAX'),
                        type=float)
    parser.add_argument('-r', '--run-simulation', action="store_true")
    parser.add_argument('-f', '--fix-simulation', action="store_true")
    parser.add_argument('-n', '--normalize', action="store_true")
    parser.add_argument('-d', '--simulation-directory', default=None)
    parser.add_argument('-p', '--probe', help='probe file to use')
    parser.add_argument('-c',
                        '--component',
                        help='component to plot',
                        choices=['Ex', 'Ey', 'Ez', 'Hx', 'Hy', 'Hz'])
    parser.add_argument('--simulation-verbosity',
                        type=int,
                        default=0,
                        help='simulation verbosity level')

    args = parser.parse_args()
    print(args)

    plot_list = []

    # read input
    sim = bfdtd.readBristolFDTD(args.infile, verbosity=args.verbosity)

    if args.fix_simulation:
        sim.fixSimulation()

    E = sim.getExcitations()[0]

    w = E.getTimeConstant()
    tau = E.getTimeOffset()
    f = E.getFrequency()
    A = E.getAmplitude()

    if args.t_range:
        t = numpy.linspace(*args.t_range, 100)
    else:
        t = numpy.array(
            utilities.common.matlab_range(-20 * w + tau, (1 / f) / 100,
                                          20 * w + tau))

    u = A * numpy.exp(-1 * numpy.power(t - tau, 2) /
                      numpy.power(w, 2)) * numpy.sin(2 * numpy.pi * f * t)
    if args.normalize:
        u = u / max(u)

    #plt.rc('text', usetex=True)
    theoretical_signal, = plt.plot(t, u, label='theoretical signal')
    plot_list.append(theoretical_signal)

    plt.xlabel('Time ($\mu s$)')
    plt.ylabel('amplitude (arbitrary units)')
    title = 'fix_simulation = {}, Excited components: {}'.format(
        args.fix_simulation, E.getExcitedComponentNames())
    plt.title(title)
    plt.show(block=False)

    if args.run_simulation:
        if args.simulation_directory:
            simulation_directory = args.simulation_directory
        else:
            simulation_directory = tempfile.mkdtemp()
        print('======================================================')
        print('simulation_directory = {}'.format(simulation_directory))
        print('======================================================')

        sim.disableAutoFix()
        sim.disableSafetyChecks()

        sim.clearFileList()
        sim.clearAllSnapshots()
        sim.clearGeometry()

        sim.setSimulationTime(sim.getExcitationEndTimeMax())
        #sim.checkSimulation()

        #sim.writeAll(simulation_directory)
        #sim.writeTorqueJobDirectory(simulation_directory)
        sim.runSimulation(simdir=simulation_directory,
                          verbosity=args.simulation_verbosity)
        print('======================================================')
        print('simulation_directory = {}'.format(simulation_directory))
        print('======================================================')

    if args.probe:
        plotProbe(args.probe,
                  component=args.component,
                  title=title,
                  plot_list=plot_list,
                  normalize=args.normalize)

    input("Press Enter to continue...")

    return 0