Example #1
0
def rf_sweep( BW, Power, Freq, Logname):
    print "rf_sweep"
    m = uut(ipaddr='10.8.9.195', opmode='master')
    s = uut(ipaddr='10.8.9.196', opmode='slave')
    m.telnet()
    s.telnet()
    m.web()
    s.web()
    print "pre control"
    ctrl = control( m, s, 25) # <-- 25 second wait time
    print "post control"

    csv = LogFile( 'logs',Logname, '.csv') #, ['11','22','33','44','55','66'] )
    tdata = testdata( 0,0,0)
    csv.write(tdata.header)
    bw   = sweep( BW[0], BW[1], BW[2], ctrl.setbw, file='bw')             
    pwr  = sweep( Power[0], Power[1], Power[2], ctrl.setpower, file='pwr')  
    frq  = sweep( Freq[0], Freq[1], Freq[2], ctrl.setfrequency, file='frq')

    bw.regen()
    ChBW = bw.next()
    while ChBW :
        print "ChBW: ",ChBW
        frq.regen() 
        delay = 25
        freq = frq.next()
        while freq:
            print "Freq: ",freq
            delay = 25
            pwr.regen() 
            power = pwr.next()
            while power:
                print "Power: ",power
                ctrl.wait(delay)
                delay = 3
                tdata = testdata( freq, power, ChBW, temp)
                tdata.wdata( m )
                tdata.wdata( s )
                csv.write(tdata.getcsv())
#                print tdata.header
                print tdata.getcsv()
                power = pwr.next()
            # reset power
            ctrl.setpower(pwr.start)
            freq = frq.next()
        ChBW = bw.next()
    print "Complete csv.close()"
    csv.close()
    bw.clean()
    pwr.clean()
    frq.clean()
Example #2
0
def main():
    conn = connect(sys.argv[1])
    n = int(sys.argv[2])

    cur = conn.cursor()
    cur.execute(
        '''CREATE TABLE IF NOT EXISTS sir_runs (
            id SERIAL PRIMARY KEY,
            gamma REAL,
            beta REAL
        )''')
    cur.execute(
        '''CREATE TABLE IF NOT EXISTS sir_results (
            id INTEGER REFERENCES sir_runs,
            s INTEGER,
            i INTEGER,
            r INTEGER,
            t SMALLINT
        );''')
    conn.commit()

    sr = sweep_range(0.99, 0.01, n)
    for g, b, sw in sweep(1000, 5, 0, sr, sr):
        print g, b, len(sw)
        cur.execute(
            '''INSERT INTO sir_runs
                (gamma, beta) VALUES (%s, %s)
                RETURNING id;''', (g, b))
        id, = cur.fetchone()
        for t in xrange(len(sw)):
            s, i, r = sw[t]
            cur.execute(
                'INSERT INTO sir_results VALUES (%s, %s, %s, %s, %s);',
                (id, s, i, r, t))
    conn.commit()
Example #3
0
def xrf_sweep():
    print "rf_sweep"
    m = uut(ipaddr='10.8.8.100', opmode='master')
    s = uut(ipaddr='10.8.8.108', opmode='slave')
    m.telnet()
    s.telnet()
    m.web()
    s.web()
    print "pre control"
    ctrl = control( m, s, 25) # <-- 25 second wait time
    print "post control"

    csv = LogFile( 'logs','SWEEP', '.csv') #, ['11','22','33','44','55','66'] )
    tdata = testdata( 0,0,0)
    csv.write(tdata.header)
    bw = sweep( 50, 51, 1, ctrl.setbw)  # <-- Channel Bandwidth 50,51,1
    ChBW = bw.next()
    while ChBW :
        print ChBW
        pwr = sweep( 10, 13, 1, ctrl.setpower) # <-- TX POWER 10,27,1
        power = pwr.next()
        while power:
            frq = sweep( 5150, 5151, 1, ctrl.setfrequency) # <-- Frequency 5150,5876,1
            freq = frq.next()
            while freq:
                print freq
                ctrl.wait()
                tdata = testdata( freq, power, ChBW)
                tdata.wdata( m )
                tdata.wdata( s )
                csv.write(tdata.getcsv())
#                print tdata.header
                print tdata.getcsv()
                freq = frq.next()
            power = pwr.next()
        ChBW = bw.next()
    csv.close()
Example #4
0
#!/usr/bin/env python3
#
# Simple spectrum analyzer to measure the transmitted spectrum
# to check that the transmitter meets frequency licensing requirements.
#
import sweep
import h5py
import numpy as n
import matplotlib.pyplot as plt

acquire_new_spec = False

if acquire_new_spec:
    import analyze_spectrum as aspec

s = sweep.sweep(freqs=sweep.freqs30, freq_dur=2.0)

n_f = len(s.freqs)

if acquire_new_spec:
    print(
        "Measuring receiver noise floor. Make sure the transmitter is powered off"
    )
    aspec.acquire_spectrum(ofname="meas/spec_off.h5", N_windows=1000)

    try:
        input(
            "Measuring the transmitted spectrum. Make sure that the transmitter is on.\n"
            "Press any key to continue.")
    except Exception as e:
        pass
Example #5
0
absM = [] #Empty list to store absolute value of magnetisation (normalised)
avgabsM = [] #Empty list to store average absolute value of magnetisation
    
iterations = 1000 #No. of sweeps we want to conduct

#To start after a few sweeps are done so that we are close to the equilibrium state 
#(and to avoid the effect of the initial state)
eqstate = int(iterations/3) 

#Set up empty lists for storing data after our chosen "equilibrium state" 
eqsweep = [] #sweep no. after "equilibrium"
eqM = [] #absolute magnetisation value after "equilibrium"

#Do multiple sweeps and store the information related to magnetisation in a list    
for i in range(iterations):
    S = sweep(S, JkT, BkT)
    
#    #For visualising lattice
#    if i%100 == 0:
#        plt.clf()
#        plt.title("i = " + str(i))
#        plt.imshow(S)
#        plt.pause(0.000001)

    M.append(np.sum(S)/maxM) #Store value of M after i sweeps
    absM.append(abs(np.sum(S)/maxM)) #Store value of |M| after i sweeps
    
    #For points after our chosen "equilibrium state"
    if i >= eqstate:
        
        eqsweep.append(i)
Example #6
0
def generate_table_all_16(algorithm):

    # If the algorithm is not supported we do not create anything
    if algorithm not in supported_algorithms:
        print("We cannot generate the table!")
    else:
        # Creating the document
        doc = Document('latex_tables/generated_table_all_16_' + algorithm)
        section = Section(algorithm_name_dict[algorithm] + " Table")

        # Creation of the Table
        table = Tabular('ccc')
        table.add_row((MultiColumn(3,
                                   align='c',
                                   data=algorithm_name_dict[algorithm]), ))
        table.add_hline()
        table.add_hline()
        table.add_row(("ID", "Soluzione", "Tempo"))
        table.add_hline()

        # Iterating for each map with respect to the wind
        map_index = 1
        for current_map in maps:
            for current_wind in winds:
                tot_cost = 0
                tot_time = 0

                # We catch the correct algorithm to use
                if algorithm == 'sweep':
                    tot_cost, tot_time, path = sweep(current_map,
                                                     generate_costs(
                                                         current_map,
                                                         current_wind),
                                                     plot=False)

                if algorithm == 'knn':
                    tot_cost, tot_time, path = kNN(
                        generate_costs(current_map, current_wind), 0)

                if algorithm == 'knn-opt':
                    tot_cost, tot_time, path = opt_kNN(
                        generate_costs(current_map, current_wind))

                if algorithm == 'nearest_insertion':
                    tot_cost, tot_time, path = nearest_insertion(
                        generate_costs(current_map, current_wind))

                if algorithm == 'farthest_insertion':
                    tot_cost, tot_time, path = farthest_insertion(
                        generate_costs(current_map, current_wind))

                # The row with the data is written onto a new row and the index is incremented
                table.add_row((map_index, "{:.2f}".format(tot_cost),
                               "{:.2e}".format(tot_time)))
                map_index += 1

        # We close the table
        table.add_hline()

        # And finally we compose and generate the new document with the embedded table
        section.append(table)
        doc.append(section)
        doc.generate_tex()
    def measure(self):
        #if self.interleaving_sequences:
        il_seqs = self.interleaving_sequences
        #else:
        #	il_seqs = [self.generate_random_interleaver_sequence(self.sequence_length) for i in range(self.random_sequence_num)]
        interleaved = [
            self.interleave(i['Gate names'], self.target_gate,
                            self.target_gate_unitary, self.target_gate_name)
            for i in il_seqs
        ]

        def set_interleaved_sequence(seq_id):
            self.tomo.set_prepare_seq(interleaved[seq_id]['Pulse sequence'])

        results = sweep.sweep(
            self.tomo, (np.arange(len(interleaved)), set_interleaved_sequence,
                        'Interleaving sequence id'),
            output=False,
            plot=False,
            header='Interleaved benchmarking sequence sweep')

        #calculating euclidean distance metric
        axes = [a for a in self.tomo.reconstruction_basis.keys()]
        expected_projections = {a:[np.trace(np.dot(self.tomo.reconstruction_basis[a]['operator'], seq['Final state matrix'])) \
               for seq in interleaved] for a in axes}
        #print (expected_projections, results)
        #print (results[axes[0]])
        #print (results[axes[0]][0])
        #print (results[axes[0]][1])
        #print (np.real(np.sqrt(np.sum([(expected_projections[a] - results[a][2])**2 for a in axes], axis=0))))
        #print (results[axes[0]][3])
        results['Euclidean distance'] = (
            results[axes[0]][0], results[axes[0]][1],
            np.real(
                np.sqrt(
                    np.sum([(expected_projections[a] - results[a][2])**2
                            for a in axes],
                           axis=0))), results[axes[0]][3])

        results['Mean Euclidean distance'] = (
            [], [],
            np.mean(
                np.real(
                    np.sqrt(
                        np.sum([(expected_projections[a] - results[a][2])**2
                                for a in axes],
                               axis=0)))), [])

        results['Pulse sequences'] = ((results[axes[0]][0], 'Gate names'),
                                      (results[axes[0]][1],
                                       np.arange(
                                           len(interleaved[0]['Gate names']))),
                                      np.asarray([
                                          i['Gate names'] for i in interleaved
                                      ]), results[axes[0]][3])

        results.update({
            '{0} fit'.format(i):
            (results[i][0], results[i][1], np.real(expected_projections[i]),
             results[i][3])
            for i in axes
        })

        # calculating fidelities of measured projections
        #psi = seq['Final state vector']
        #results['Fidelity'] = np.sqrt(np.sum([np.einsum('i,ij,jk,kl,j->', np.conj(psi), np.conj(Ut['unitary']), rho, Ut['unitary'], psi) \
        #							for rho, Ut in zip(, self.tomo.proj_seq)]))

        #for a in axes:
        #	plt.close(a)
        #for p in self.tomo.proj_seq.keys():
        #	plt.close(a)

        return {k: v[2] for k, v in results.items()}
    output_file = file(output_filename,'w')
    output_file.write("#PWIDTH\tPWIDTH Error\tPIN\tPIN Error\tWIDTH\tWIDTH Error\tRISE\tRISE Error\tFALL\tFALL Error\tAREA\tAREA Error\tMinimum\tMinimum Error\n")

    #Start scanning!
    tmpResults = None
    t_start = time.time()
    for width in widths:
        min_volt = None
        loopStart = time.time()
        if tmpResults!=None:
            #set a best guess for the trigger and the scale
            #using the last sweeps value
            min_volt = float(tmpResults["peak"])
            if min_volt == 0: # If bad data set, make none
                min_volt = 50e-3 # Used to be None - Changed for speed-up!
        tmpResults = sweep.sweep(saveDir,box,channel,width,delay,scope,min_volt)
                
        output_file.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(width, 0,
                                            tmpResults["pin"], tmpResults["pin error"],
                                            tmpResults["width"], tmpResults["width error"],
                                            tmpResults["rise"], tmpResults["rise error"],
                                            tmpResults["fall"], tmpResults["fall error"],
                                            tmpResults["area"], tmpResults["area error"],
                                            tmpResults["peak"], tmpResults["peak error"] ))

        print "WIDTH %d took : %1.1f s" % (width, time.time()-loopStart)

    output_file.close()

    print "Total script time : %1.1f mins"%( (time.time() - total_time) / 60)
    
Example #9
0
    output_file = file(output_filename,'w')

    output_file.write("#PWIDTH\tPIN\tWIDTH\tRISE\tFALL\tWIDTH\tAREA\n")

    #Start scanning!
    widths = range(cutoff-1500,cutoff+501,10)
    results = None

    sweep.set_port(options.port)
    sweep.set_scope("LeCroy")
    sweep.start()

    for width in widths:
        min_volt = None
        print time.time()
        if results!=None:
            #set a best guess for the trigger and the scale
            #using the last sweeps value
            min_volt = float(results["minimum"]) 
        results = sweep.sweep("low_intensity",output_filename,box,channel,width,delay,scope,min_volt,min_trigger)    
        output_file.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(width,
                                                      results["pin"],
                                                      results["width"],
                                                      results["rise"],
                                                      results["fall"],
                                                      results["width"],
                                                      results["area"]))
    output_file.close()
    
    
Example #10
0
    nearest_neighbour_opt_curr_cost = 0
    nearest_neighbour_opt_curr_time = 0
    nearest_insertion_curr_cost = 0
    nearest_insertion_curr_time = 0
    farthest_insertion_curr_cost = 0
    farthest_insertion_curr_time = 0

    for i in range(n_means):

        print(" = Generating maps for " + str(dim) + " nodes =")
        current_map = generate_map(dim)

        # Uptating Sweep
        print("Generating sweep...")
        c, t, _ = sweep(current_map,
                        generate_costs(current_map, 0),
                        plot=False)
        sweep_curr_cost += c
        sweep_curr_time += t
        print("Sweep time: " + "{:.2f}".format(t))

        # Uptating Nearest Neighbour
        print("Generating nearest neighbour...")
        c, t, _ = kNN(generate_costs(current_map, 0), 0)
        nearest_neighbour_curr_cost += c
        nearest_neighbour_curr_time += t
        print("Nearest neighbour time: " + "{:.2f}".format(t))

        # Uptating Optimized Nearest Neighbour
        print("Generating optimized nearest neighbour...")
        c, t, _ = opt_kNN(generate_costs(current_map, 0))
Example #11
0
def rf_sweep_temp( BW, Power, Freq, Temp, Logname):
    print "rf_sweep_temp"
    m = uut(ipaddr='10.8.8.100', opmode='master') #195
    s = uut(ipaddr='10.8.8.108', opmode='slave') #196
    m.telnet()
    s.telnet()
    m.web()
    s.web()
    t = None
    # is the thermotron required? 
    if Temp[0] != Temp[1]:
        t = thermotron("10.8.9.20")
        print "thermotron"
    ctrl = control( m, s, t, 25) # <-- 25 second wait time

    csv = LogFile( 'logs',Logname, '.csv') #, ['11','22','33','44','55','66'] )
    tdata = testdata( 0,0,0,'--')
    csv.write(tdata.header)
    thm  = sweep( Temp[0], Temp[1], Temp[2], ctrl.settemp, file='thm')             
    bw   = sweep( BW[0], BW[1], BW[2], ctrl.setbw, file='bw')             
    pwr  = sweep( Power[0], Power[1], Power[2], ctrl.setpower, file='pwr')  
    frq  = sweep( Freq[0], Freq[1], Freq[2], ctrl.setfrequency, file='frq')

    thm.regen()
    temp = thm.next()
    print
    while temp:
        print "Temp"
        bw.regen()
        ChBW = bw.next()
        while ChBW :
            print "ChBW: ",ChBW
            frq.regen() 
            delay = 25
            freq = frq.next()
            while freq:
                
                print "Freq: ",freq
                delay = 25
                pwr.regen() 
                power = pwr.next()
                while power:
                    if freq < 5750 and power >= 23:
                        pwr.curval = None
                        pwr.regen()
                        break;
                    print "Power: ",power
                    ctrl.wait(delay)
                    delay = 3
                    tdata = testdata( freq, power, ChBW, temp)
                    tdata.wdata( m )
                    tdata.wdata( s )
                    csv.write(tdata.getcsv() )
    #                print tdata.header
                    print tdata.getcsv()
                    power = pwr.next()
                # reset power
                ctrl.setpower(pwr.start)
                freq = frq.next()
            ChBW = bw.next()
        temp = thm.next()
    print "Complete csv.close()"
    csv.close()
    bw.clean()
    pwr.clean()
    frq.clean()
    thm.clean()
Example #12
0
import channels
import numpy
import sweep
import channel_panel_gui
import sweep_gui


sw1 = sweep.sweep("D244_2Dsweep", [VG1, VG2], [I1], loops="2", updatepointbypoint=True)

sw1.set_loops([0.1, 0.3, 0.05], 0)
sw1.set_channel_factors([1, 1], 0)

# sw1.add_final_coord([[0.2,0.4]],0)

# sw1.add_final_coord([[0.4,0.2],[0.2,0.4]],1)


sw1.set_loops([0, 0.2, 0.05], 1)
sw1.set_channel_factors([0, 1], 1)

# sw1.set_loops([0,0.2,0.05],2)
# sw1.set_channel_factors([0,1,0],2)

# sw1.set_loops([0,0.2,0.05],3)
# sw1.set_channel_factors([0,1,0],3)


sw1.set_channel_constants([0, 0])

channel_panel_gui.channel_panel([VSD, VG1, VG2, VG3])
sweep_gui.sweep_gui(sw1)
Example #13
0
    usb_conn = scope_connections.VisaUSB()
    scope = scopes.Tektronix3000(usb_conn)
    scope.set_cursor("x", 1, cursor_low)
    scope.set_cursor("x", 2, cursor_high)

    #Create a new, timestamped, summary file
    timestamp = time.strftime("%y%m%d_%H.%M.%S", time.gmtime())
    output_filename = "broad/Box%02d_Channel%d_%s.dat" % (box, channel,
                                                          timestamp)
    output_file = file(output_filename, 'w')

    output_file.write("#PWIDTH\tPIN\tWIDTH\tRISE\tFALL\tWIDTH\tAREA\n")

    #Start scanning!
    widths = range(0, cutoff + 501, 50)
    results = None

    for width in widths:
        min_volt = None
        if results != None:
            #set a best guess for the trigger and the scale
            #using the last sweeps value
            min_volt = float(results["minimum"])
        results = sweep.sweep("broad", output_filename, box, channel, width,
                              delay, scope, min_volt, min_trigger)
        output_file.write(
            "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" %
            (width, results["pin"], results["width"], results["rise"],
             results["fall"], results["width"], results["area"]))
    output_file.close()
Example #14
0
    def __init__(self, fname=None, write_waveforms=True, quiet=True):
        c = configparser.ConfigParser()
        self.quiet = quiet
        if fname is not None:
            if os.path.exists(fname):
                if not quiet:
                    print("reading %s" % (fname))
                c.read(fname)
            else:
                print("configuration file %s doesn't exist." % (fname))
                exit(0)

        self.fname = fname
        self.instrument_name = json.loads(c["config"]["instrument_name"])
        self.n_range_gates = int(json.loads(c["config"]["n_range_gates"]))
        self.station_id = json.loads(c["config"]["station_id"])

        self.lat = int(json.loads(c["config"]["lat"]))
        self.lon = int(json.loads(c["config"]["lon"]))
        self.require_gps = bool(json.loads(c["config"]["require_gps"]))
        self.save_raw_voltage = bool(
            json.loads(c["config"]["save_raw_voltage"]))
        self.min_gps_lock_time = json.loads(c["config"]["min_gps_lock_time"])

        self.rx_channel = json.loads(c["config"]["rx_channel"])

        self.sample_rate = int(json.loads(c["config"]["sample_rate"]))
        self.dec = int(json.loads(c["config"]["dec"]))

        self.data_dir = json.loads(c["config"]["data_dir"])

        self.range_shift = int(json.loads(c["config"]["range_shift"]))

        #        self.codes=json.loads(c["config"]["codes"])
        self.short_name = json.loads(c["config"]["short_name"])

        self.code_len = json.loads(c["config"]["code_len"])
        self.code_types = json.loads(c["config"]["code_type"])
        self.pulse_lengths = json.loads(c["config"]["pulse_length"])
        self.ipps = json.loads(c["config"]["ipp"])
        self.bws = json.loads(c["config"]["bw"])

        if not quiet:
            print("Creating waveforms")
        self.n_codes = len(self.code_types)
        self.codes = []
        self.orig_codes = []
        for i in range(self.n_codes):
            if self.pulse_lengths[i] > 0:
                if n.mod(int(self.code_len), int(self.ipps[i])) != 0:
                    print("Code length %d must be a multiple of IPP %d."
                          " This is not the case. Exiting." %
                          (self.code_len, self.ipps[i]))
                    exit(0)
            # todo. we should avoid dumping the waveforms to files
            # for all but debugging purposes. the waveforms
            # created here (ocode) should be directly fed into sweep.
            cfname, ocode = create_waveform.waveform_to_file(
                station=self.station_id,
                clen=self.code_len,
                oversample=self.dec,
                filter_output=True,
                sr=self.sample_rate,
                bandwidth=self.bws[i],
                power_outside_band=0.01,
                pulse_length=self.pulse_lengths[i],
                ipp=self.ipps[i],
                code_type=self.code_types[i],
                write_file=write_waveforms)

            self.codes.append(cfname)
            self.orig_codes.append(ocode)

        self.freqs = json.loads(c["config"]["freqs"])
        self.n_freqs = len(self.freqs)
        for fi in range(len(self.freqs)):
            # center frequency
            self.freqs[fi][0] = float(self.freqs[fi][0])
            # code index
            self.freqs[fi][1] = int(self.freqs[fi][1])

        self.transmit_amplitude = float(
            json.loads(c["config"]["transmit_amplitude"]))

        self.frequency_duration = float(
            json.loads(c["config"]["frequency_duration"]))

        if n.mod(int(self.frequency_duration * self.sample_rate),
                 int(self.code_len * self.dec)) != 0:
            print(
                "frequency_duration (%1.2f s) needs to be a multiple of code_length (%1.2f s)"
                % (self.frequency_duration,
                   self.code_len * self.dec / self.sample_rate))
            exit(0)

        self.antenna_select_freq = float(
            json.loads(c["config"]["antenna_select_freq"]))

        self.max_plot_range = float(json.loads(c["config"]["max_plot_range"]))

        self.gps_holdover_time = float(
            json.loads(c["config"]["gps_holdover_time"]))

        self.max_plot_dB = float(json.loads(c["config"]["max_plot_dB"]))

        self.tx_addr = json.loads(c["config"]["tx_addr"])
        self.rx_addr = json.loads(c["config"]["rx_addr"])

        self.tx_subdev = json.loads(c["config"]["tx_subdev"])
        self.rx_subdev = json.loads(c["config"]["rx_subdev"])

        self.ionogram_path = json.loads(c["config"]["ionogram_path"])
        self.ionogram_dirname = json.loads(c["config"]["ionogram_dirname"])

        self.reflected_power_cal_dB = json.loads(
            c["config"]["reflected_power_cal_dB"])

        try:
            os.mkdir(self.ionogram_path)
        except Exception as e:
            pass

        if not os.path.exists(self.ionogram_path):
            print("Output directory %s doesn't exists and cannot be created" %
                  (self.ionogram_path))
            exit(0)
        try:
            os.mkdir(self.ionogram_path)
        except Exception as e:
            pass

        if not os.path.exists(self.data_dir):
            print("Output directory %s doesn't exists and cannot be created" %
                  (self.data_dir))
            exit(0)

        self.s = sweep.sweep(
            freqs=self.freqs,
            codes=self.codes,
            sample_rate=self.sample_rate,
            code_amp=self.
            transmit_amplitude,  # safe setting for waveform amplitude
            freq_dur=self.frequency_duration)
    saveDir = sweep.check_dir("data/scope_data_%1.2fV/" % float(options.voltage))
    sweep.check_dir("%sraw_data/" % saveDir)
    output_filename = "%s/Chan%02d_%1.2fV.dat" % (saveDir,channel,float(options.voltage))
    output_file = file(output_filename,'w')
    output_file.write("#PWIDTH\tPWIDTH Error\tPIN\tPIN Error\tWIDTH\tWIDTH Error\tRISE\tRISE Error\tFALL\t\
FALL Error\tAREA\tAREA Error\tMinimum\tMinimum Error\n")

    flag, tmpResults, min_volt = 0, None, None
    run_start = time.time()
    for width in widths:
        loop_start = time.time()
        if tmpResults!=None:
            #set a best guess for the trigger and the scale
            #using the last sweeps value
            min_volt = float(tmpResults["peak"])

        tmpResults = sweep.sweep(saveDir,1,channel,width,pulse_delay_ms,scope,min_volt)        

        output_file.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(width, 0,
                                            tmpResults["pin"], 0,
                                            tmpResults["width"], tmpResults["width error"],
                                            tmpResults["rise"], tmpResults["rise error"],
                                            tmpResults["fall"], tmpResults["fall error"],
                                            tmpResults["area"], tmpResults["area error"],
                                            tmpResults["peak"], tmpResults["peak error"] ))

        print "WIDTH %d took : %1.1f s" % (width, time.time()-loop_start)

    output_file.close()
    print "Total script time : %1.1f mins"%( (time.time() - total_time) / 60)
Example #16
0
    def __init__(self, fname=None, write_waveforms=True, quiet=True):
        c = configparser.ConfigParser()
        self.quiet = quiet
        if fname != None:
            if os.path.exists(fname):
                if not quiet:
                    print("reading %s" % (fname))
                c.read(fname)
            else:
                print("configuration file %s doesn't exist." % (fname))
                exit(0)

        self.fname = fname
        self.instrument_name = json.loads(c["config"]["instrument_name"])
        self.n_range_gates = int(json.loads(c["config"]["n_range_gates"]))
        self.station_id = json.loads(c["config"]["station_id"])

        self.lat = int(json.loads(c["config"]["lat"]))
        self.lon = int(json.loads(c["config"]["lon"]))
        self.require_gps = bool(json.loads(c["config"]["require_gps"]))
        self.save_raw_voltage = bool(
            json.loads(c["config"]["save_raw_voltage"]))
        self.min_gps_lock_time = json.loads(c["config"]["min_gps_lock_time"])

        self.rx_channel = json.loads(c["config"]["rx_channel"])

        self.sample_rate = int(json.loads(c["config"]["sample_rate"]))
        self.dec = int(json.loads(c["config"]["dec"]))

        self.data_dir = json.loads(c["config"]["data_dir"])

        self.range_shift = int(json.loads(c["config"]["range_shift"]))

        #        self.codes=json.loads(c["config"]["codes"])
        self.short_name = json.loads(c["config"]["short_name"])

        self.code_len = json.loads(c["config"]["code_len"])
        self.code_types = json.loads(c["config"]["code_type"])
        self.pulse_lengths = json.loads(c["config"]["pulse_length"])
        self.ipps = json.loads(c["config"]["ipp"])
        self.bws = json.loads(c["config"]["bw"])

        if not quiet:
            print("Creating waveforms")
        self.n_codes = len(self.code_types)
        self.codes = []
        self.orig_codes = []
        for i in range(self.n_codes):
            cfname, ocode = create_waveform.waveform_to_file(
                station=self.station_id,
                clen=self.code_len,
                oversample=self.dec,
                filter_output=True,
                sr=self.sample_rate,
                bandwidth=self.bws[i],
                power_outside_band=0.01,
                pulse_length=self.pulse_lengths[i],
                ipp=self.ipps[i],
                code_type=self.code_types[i],
                write_file=write_waveforms)

            self.codes.append(cfname)
            self.orig_codes.append(ocode)

        self.freqs = json.loads(c["config"]["freqs"])
        self.n_freqs = len(self.freqs)
        for fi in range(len(self.freqs)):
            # center frequency
            self.freqs[fi][0] = float(self.freqs[fi][0])
            # code index
            self.freqs[fi][1] = int(self.freqs[fi][1])

        self.transmit_amplitude = float(
            json.loads(c["config"]["transmit_amplitude"]))

        self.frequency_duration = json.loads(c["config"]["frequency_duration"])

        self.antenna_select_freq = float(
            json.loads(c["config"]["antenna_select_freq"]))

        self.gps_holdover_time = float(
            json.loads(c["config"]["gps_holdover_time"]))

        self.tx_addr = json.loads(c["config"]["tx_addr"])
        self.rx_addr = json.loads(c["config"]["rx_addr"])

        self.tx_subdev = json.loads(c["config"]["tx_subdev"])
        self.rx_subdev = json.loads(c["config"]["rx_subdev"])

        self.ionogram_path = json.loads(c["config"]["ionogram_path"])

        self.reflected_power_cal_dB = json.loads(
            c["config"]["reflected_power_cal_dB"])

        try:
            os.mkdir(self.ionogram_path)
        except:
            pass

        if not os.path.exists(self.ionogram_path):
            print("Output directory %s doesn't exists and cannot be created" %
                  (self.ionogram_path))
            exit(0)
        try:
            os.mkdir(self.ionogram_path)
        except:
            pass

        if not os.path.exists(self.data_dir):
            print("Output directory %s doesn't exists and cannot be created" %
                  (self.data_dir))
            exit(0)

        self.s = sweep.sweep(
            freqs=self.freqs,
            codes=self.codes,
            sample_rate=self.sample_rate,
            code_amp=self.
            transmit_amplitude,  # safe setting for waveform amplitude
            freq_dur=self.frequency_duration)
Example #17
0
    scope.set_cursor("x",2,cursor_high)
    
    #Create a new, timestamped, summary file
    timestamp = time.strftime("%y%m%d_%H.%M.%S",time.gmtime())
    output_filename = "broad/Box%02d_Channel%d_%s.dat" % (box,channel,timestamp)
    output_file = file(output_filename,'w')

    output_file.write("#PWIDTH\tPIN\tWIDTH\tRISE\tFALL\tWIDTH\tAREA\n")

    #Start scanning!
    widths = range(0,cutoff+501,50)
    results = None

    for width in widths:
        min_volt = None
        if results!=None:
            #set a best guess for the trigger and the scale
            #using the last sweeps value
            min_volt = float(results["minimum"])
        results = sweep.sweep("broad",output_filename,box,channel,width,delay,scope,min_volt,min_trigger)    
        output_file.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n"%(width,
                                                      results["pin"],
                                                      results["width"],
                                                      results["rise"],
                                                      results["fall"],
                                                      results["width"],
                                                      results["area"]))
    output_file.close()
    
    
#	Change log
#	Need to add a button for reset
#	Need to add a button for sweep
#	Need to add a button for ultrasonic transmit

from Tkinter import *
import project3
import sweep

p = project3.project3()
s = sweep.sweep()

def spin_servo():
    p.set_vals(x.get(), y.get())
    root.after(100,spin_servo)

root = Tk()
y = Scale(root, from_=65535, to=0)
y.pack(anchor=CENTER)
x = Scale(root, from_=0, to=65535, orient=HORIZONTAL)
x.pack(anchor=CENTER)
Button(root, text='Sweep', command=s.move).pack()
#Button(root, text = 'Stop Sweep',command=s.stop).pack()

root.after(100,spin_servo)
root.mainloop()
    #Start scanning!
    #widths = range(0,9000,step)
    widths = range(0, 10000, step)
    tmpResults = None

    t_start = time.time()
    for width in widths:
        min_volt = None
        loopStart = time.time()
        if tmpResults != None:
            #set a best guess for the trigger and the scale
            #using the last sweeps value
            min_volt = float(tmpResults["peak"])
            if min_volt == 0:  # If bad data set, make none
                min_volt = 50e-3  # Used to be None - changed for speed up!
        tmpResults = sweep.sweep(saveDir, box, channel, width, delay, scope,
                                 min_volt)

        #results.set_meta_data("area", tmpResults["area"])
        #results.set_meta_data("area error", tmpResults["area error"])

        output_file.write(
            "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" %
            (width, 0, tmpResults["pin"], tmpResults["pin error"],
             tmpResults["width"], tmpResults["width error"],
             tmpResults["rise"], tmpResults["rise error"], tmpResults["fall"],
             tmpResults["fall error"], tmpResults["area"],
             tmpResults["area error"], tmpResults["peak"],
             tmpResults["peak error"]))

        print "WIDTH %d took : %1.1f s" % (width, time.time() - loopStart)
Example #20
0
qt_dir = "D:/qtlab_replacement"
sys.path.append(qt_dir)
import init
from instruments import *
import sweep
import time

CS_Vlim = 10.
currents = arange(0, -0.5, -0.005)
pna = Agilent_N5242A('pna', address='pna')
#cs = Yokogawa_GS210(address='gs210')

rm = visa.ResourceManager()
CS = rm.open_resource("2651")
CS.write('''smua.source.func = smua.OUTPUT_DCAMPS;
smua.source.limitv = {:f};
smua.source.autorangei = smua.AUTORANGE_ON;
smua.source.leveli = 0;
smua.source.output = smua.OUTPUT_ON;
'''.format(CS_Vlim))


def set_current(I):
    CS.write("smua.source.leveli = {:e}".format(I))
    time.sleep(10)


sweep.sweep(pna, (currents, set_current, 'Current'), filename='test')
#cs.set_current(0)
CS.write('''smua.source.leveli = 0;
smua.source.output = smua.OUTPUT_OFF;''')
Example #21
0
def characterize_location(ls):
    sweep_val = sweep.sweep()
    print("finished sweep")

    for i in range(len(ls.sig)):
        ls.sig[i] = sweep_val[i]
Example #22
0
def generate_loss_wrt_optimum():

    # Creating the document
    from_mode = ''
    doc = Document('latex_tables/generated_loss_wrt_optimum')
    section = Section("Table of Costs")
    from_mode = "{:.2f}"

    # Setting tabular property
    tabular_header = 'cccccc'

    # Creation of the Table
    table = Tabular(tabular_header)
    table.add_row((MultiColumn(6, align='c', data='Costs'), ))
    table.add_hline()
    table.add_hline()
    table.add_row(['ID'] + supported_algorithms)
    table.add_hline()

    # Iterating for each map with respect to the wind
    map_index = 1

    for current_map in maps:
        for current_wind in winds:

            # We catch the correct algorithm to use
            tot_cost_0, _, _ = sweep(current_map,
                                     generate_costs(current_map, current_wind),
                                     plot=False)
            tot_cost_1, _, _ = kNN(generate_costs(current_map, current_wind),
                                   0)
            tot_cost_2, _, _ = opt_kNN(
                generate_costs(current_map, current_wind))
            tot_cost_3, _, _ = nearest_insertion(
                generate_costs(current_map, current_wind))
            tot_cost_4, _, _ = farthest_insertion(
                generate_costs(current_map, current_wind))

            # The row with the data is written onto a new row and the index is incremented
            print(map_index)
            table.add_row(
                (map_index, "{:.2f}".format(
                    ((tot_cost_0 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_1 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_2 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_3 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%', "{:.2f}".format(
                     ((tot_cost_4 / real_optimum[map_index - 1]) - 1) * 100) +
                 '%'))

            map_index += 1

    # We close the table
    table.add_hline()

    # And finally we compose and generate the new document with the embedded table
    section.append(table)
    doc.append(section)
    doc.generate_tex()
Example #23
0
currents = arange(-1, 1, 0.01) * 1e-3

pna_preset = True

cs = Yokogawa_GS210(address='GPIB0::2::INSTR')
pna = Agilent_N5242A('pna', address='pna')

cs.set_range(1e-3)
pna.set_sweep_mode("LIN")
if pna_preset:
    pna.set_nop(400)
    pna.set_power(-30.)
    pna.set_bandwidth(200)
    pna.set_centerfreq(6.6644e9)
    pna.set_span(50e6)

cs.set_status(1)


def set_current(val):
    cs.set_current(0.)
    time.sleep(0.02)
    cs.set_current(val)


sweep.sweep(pna, (currents, set_current, 'Current'))

cs.set_current(0.)
cs.set_status(0)
pna.close()
Example #24
0
require_gps = True

# minimum safe wait is 5 mins
min_gps_lock_time = 300
# gps acquisition time can be reduced for testing purposes
min_gps_lock_time = 0

# sweep definition
# todo: add code definition here.

if True:
    s = sweep.sweep(
        freqs=sweep.freqstiming,
        codes=[
            "waveforms/code-l10000-b10-000000f_100k.bin",
            "waveforms/code-l10000-b10-000000f_50k.bin",
            "waveforms/code-l10000-b10-000000f_30k.bin"
        ],
        sample_rate=sample_rate,
        code_amp=0.8,  # safe setting for waveform amplitude
        freq_dur=4.0)

# single frequency test
if False:
    s = sweep.sweep(freqs=[[5.305, 5.335, 0]],
                    codes=["waveforms/code-l10000-b10-000000f_30k.bin"],
                    code_amp=0.5,
                    freq_dur=60.0)  # This is for OBW measurements

# ram disk to store about two ionosonde cycles worth of data
data_path = "/media/data"