def test_sample_11(self): code = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9] amplifier = Amplifier(code) status, signal = amplifier.execute(1) self.assertEqual(status, 'OUTPUT') self.assertEqual(signal, 1) status, signal = amplifier.execute() self.assertEqual(status, 'HALT') self.assertEqual(signal, None)
def test_wait(self): code = [3, 3, 99, 0] amplifier = Amplifier(code) status, signal = amplifier.execute() self.assertEqual(status, 'WAITING') self.assertEqual(signal, None) status, signal = amplifier.execute(10) self.assertEqual(status, 'HALT') self.assertEqual(signal, None)
def test_io(self): code = [3, 9, 1002, 9, 2, 10, 4, 10, 99, 0, 0] amplifier = Amplifier(code) status, signal = amplifier.execute(3) self.assertEqual(status, 'OUTPUT') self.assertEqual(signal, 6) status, signal = amplifier.execute() self.assertEqual(status, 'HALT') self.assertEqual(signal, None)
def test_sample_9(self): code = [3, 3, 1107, -1, 8, 3, 4, 3, 99] amplifier = Amplifier(code) status, signal = amplifier.execute(0) self.assertEqual(status, 'OUTPUT') self.assertEqual(signal, 1) status, signal = amplifier.execute() self.assertEqual(status, 'HALT') self.assertEqual(signal, None)
def read_in_raw(args): log = logging.getLogger('characterize') # Check that the arguments are filled if args.specid: args.specid = "%03d" % int(args.specid) else: msg = 'No SPECID was provided.' log.error(msg) labels = ['dir_date', 'dir_obsid', 'dir_expnum'] observations = ['bia', 'drk', 'pxf', 'ptc', 'flt'] for obs in observations: amp_list = [] for label in labels[:2]: getattr(args, obs + label) if getattr(args, obs + label) is None: msg = '%s%s was not provided' % (obs, label) log.error(msg) else: setattr(args, obs + label, getattr(args, obs + label).replace(" ", "").split(',')) if getattr(args, obs + labels[2]) is not None: setattr(args, obs + labels[2], getattr(args, obs + labels[2]).replace(" ", "").split(',')) for date in getattr(args, obs + labels[0]): for obsid in getattr(args, obs + labels[1]): if getattr(args, obs + labels[2]) is not None: for expnum in getattr(args, obs + labels[2]): folder = op.join( date, args.instr, "{:s}{:07d}".format(args.instr, int(obsid)), "exp{:02d}".format(int(expnum)), args.instr) files = sorted( glob.glob(op.join(args.rootdir, folder, '*'))) for fn in files: amp_list.append(Amplifier(fn, '', name=obs)) amp_list[-1].subtract_overscan() amp_list[-1].trim_image() else: folder = op.join( date, args.instr, "{:s}{:07d}".format(args.instr, int(obsid))) files = sorted( glob.glob( op.join(args.rootdir, folder, '*', args.instr, '*'))) for fn in files: amp_list.append(Amplifier(fn, '', name=obs)) amp_list[-1].subtract_overscan() amp_list[-1].trim_image() setattr(args, obs + '_list', amp_list) return args
def main(): text_input = get_raw_input() amplifier_controller_software = [int(x) for x in text_input.split(',')] phase_settings = [5, 6, 7, 8, 9] amplifiers = [] for _ in range(len(phase_settings)): amplifiers.append(Amplifier(amplifier_controller_software)) for n in range(len(amplifiers) - 1): amplifiers[n].next_amplifier = amplifiers[n + 1] amplifiers[-1].next_amplifier = amplifiers[0] outputs = [] for phase_setting_sequence in get_all_arrangements(phase_settings): for i in range(len(phase_setting_sequence)): amplifiers[i].reset() amplifiers[i].add_input(phase_setting_sequence[i]) amplifiers[0].add_input(0) while not amplifiers[-1].finished: for amplifier in amplifiers: amplifier.amplify_till_halt() outputs.append(amplifiers[-1].last_output) print('Max thruster signal:', max(outputs))
def initialize(phase_sequence, code): """Return amplifiers initialized according to phase sequence. Assumes that upon initialization, amplifiers will have no output. """ amplifiers = [Amplifier(code) for _ in range(5)] for amp, phase in zip(amplifiers, phase_sequence): amp.execute(phase) return amplifiers
def main(file): lst = [int(item) for item in file.read().split(',')] best = {"permutation": None, "output": 0} for permutation in generatePhasePermutation(5, [0, 1, 2, 3, 4]): amplifiers = [Amplifier(phase) for phase in permutation] io = 0 for amplifier in amplifiers: io = amplifier.process(lst, io) if (best['output'] < io): best['output'] = io best['permutation'] = permutation print('best:', best['permutation'], best['output'])
def __init__( self, freq=440.0, level=1.0, phase=0.0, feedback=0, wave_type='sine', fm_type='DX', gate=Gate([0.0]), key_in=None ): Oscillator.__init__(self, key_in) self.freq = freq #frequency self.mixer = Mixer() #mixer to add modulators' outputs #sound generator if fm_type == 'LinearFM': self.generator = LinearFMGenerator( freq, level, phase, wave_type, self.mixer, key_in ) elif fm_type == 'DX': self.generator = DXGenerator( freq, level, phase, wave_type, self.mixer, key_in ) self.eg = ADSR(input=gate) #envelope generator #amplifier self.amp = Amplifier(input=self.generator, mod=self.eg)
def main(): amp = Amplifier("Top-O-Line-Amplifier") tuner = Tuner("Top-O-Line AM/FM Tuner", amp) dvd_player = DvdPlayer("Top-O-Line DVD Player", amp) cd_player = CDPlayer("Top-O-Line CD Player", amp) projector = Projector("Top-O-Line Projector", dvd_player) lights = TheaterLights("Theater Ceiling Lights") screen = Screen("Theater Screen") popper = PopcornPopper("Popcorn Popper") home_theater = HomeTheaterFacade(amp, tuner, dvd_player, cd_player, projector, screen, lights, popper) home_theater.watch_movie("Lord of the Rings") print() home_theater.end_movie() print()
def run_iteration(iteration): output_signal = 0 input_signal = 0 amplifiers = {} while True: for ampNumber in range(1, 6): if ampNumber not in amplifiers: amplifiers[ampNumber] = Amplifier(example_opcodes) input = [iteration[ampNumber - 1], input_signal] else: input = [input_signal] current_amplifier = amplifiers[ampNumber] output_signal = current_amplifier.run_int_code(input) # print("amplifier " + str(ampNumber) + " gave output: " + str(output_signal)) input_signal = output_signal if (current_amplifier.halted == True): return input
def main(): filename = "input.txt" feedback = False if len(sys.argv) > 1: filename = sys.argv[1] if len(sys.argv) > 2 and sys.argv[2] == "--feedback": feedback = True f = open(filename) s = f.readline() memory = list(map(int, s.split(","))) maxSignal = 0 result = None signal = 0 permutations = None if not feedback: permutations = itertools.permutations(range(5), 5) else: permutations = itertools.permutations(range(5, 10), 5) for perm in permutations: signal = 0 amplifiers = [] for i in range(len(perm)): amplifiers.append(Amplifier("{}".format(i), memory, perm[i])) running = True while running: terminated = True for a in amplifiers: out = a.amplify(signal) if out != None: signal = out terminated &= a.terminated() running = not terminated if maxSignal < signal: maxSignal = signal result = perm print("Result signal: {}".format(maxSignal)) print("Combination: {}".format(result))
class FMOperator(Oscillator): """A class to represent an FM operator""" def __init__( self, freq=440.0, level=1.0, phase=0.0, feedback=0, wave_type='sine', fm_type='DX', gate=Gate([0.0]), key_in=None ): Oscillator.__init__(self, key_in) self.freq = freq #frequency self.mixer = Mixer() #mixer to add modulators' outputs #sound generator if fm_type == 'LinearFM': self.generator = LinearFMGenerator( freq, level, phase, wave_type, self.mixer, key_in ) elif fm_type == 'DX': self.generator = DXGenerator( freq, level, phase, wave_type, self.mixer, key_in ) self.eg = ADSR(input=gate) #envelope generator #amplifier self.amp = Amplifier(input=self.generator, mod=self.eg) def add_modulator(self, mod, level=1.0): """Adds a modulator""" self.mixer.add_input(mod, level) def set_key_in(self, key_in): """Sets key input""" self.key_in = key_in self.generator.set_key_in(key_in) def set_eg_params(self, *args, **kwargs): """Sets parameters of the envelope""" self.eg.set_params(*args, **kwargs) def set_gate(self, gate): """Sets the gate input""" self.eg.set_input(gate) def set_keyboard(self, keyboard): """sets key and gate input from a keybord""" self.set_key_in(keyboard.key) self.set_gate(keyboard.gate) def output(self, t, **kwargs): """Returns the value of operators signal in time t""" return self.amp.output(t, **kwargs) def draw(self, ax, time=None, cycles=1, **kwargs): """ Draws the shape of the operators output signal along with its modulators and modulators' modulators etc. If 'time' is not provided, the shape will be drawn for 'cycles' cycles of operators carrier generator """ #draw the operators output signal Oscillator.draw(self, ax, time, cycles, **kwargs) #draw modulators' output signals if time is None: time = cycles / np.float64(self.freq) try: kwargs['alpha'] *= 0.5 except KeyError: kwargs['alpha'] = 0.5 self.mixer.draw(ax, time, **kwargs)
import aoc_download from intcode_computer import IntCodeComputer from custom_enums import Opcode from amplifier import Amplifier YEAR = 2019 DAY = 7 puzzle_input = aoc_download.aoc.puzzle_input_file(YEAR, DAY) amp_a = Amplifier(puzzle_input) amp_b = Amplifier(puzzle_input) amp_c = Amplifier(puzzle_input) amp_d = Amplifier(puzzle_input) amp_e = Amplifier(puzzle_input) max_output = 0 for phase_a in range(5): for phase_b in range(5): if phase_b in [phase_a]: continue for phase_c in range(5): if phase_c in [phase_a, phase_b]: continue for phase_d in range(5): if phase_d in [phase_a, phase_b, phase_c]: continue
from amplifier import Amplifier from cd_player import CdPlayer from dvd_player import DvdPlayer from home_theater_facade import HomeTheaterFacade from tuner import Tuner amplifier = Amplifier() cd = CdPlayer() dvd = DvdPlayer() tuner = Tuner() facade = HomeTheaterFacade(tuner, amplifier, cd, dvd) facade.watch_movie() facade.listen_to_cd() facade.listen_to_radio() facade.end_radio()
def __init__(self, topo='cian', link_length=1, span_length=1, channels=None): """ :param topo: topology to be used :param link_length: only used when topo='linear :param span_length: only used when topo='linear :param channels: only used when topo='linear """ # Create a Network object self.net = Network() if topo == 'cian': nodes = [] # Create the nodes of the network self.n1 = Node(1, amplifier=Amplifier(target_gain=9)) # Tx node nodes.append(self.n1) self.n2 = Node(2, amplifier=Amplifier(target_gain=9)) # in-line node nodes.append(self.n2) self.n3 = Node(3) # in-line node nodes.append(self.n3) self.n4 = Node(4, amplifier=Amplifier(target_gain=18)) # in-line node nodes.append(self.n4) self.n5 = Node(5, amplifier=Amplifier(target_gain=18)) # in-line node nodes.append(self.n5) self.n6 = Node(6, amplifier=Amplifier(target_gain=9)) # in-line node nodes.append(self.n6) self.n7 = Node(7) # in-line node nodes.append(self.n7) self.n8 = Node(8) # Rx node nodes.append(self.n8) # Add nodes to the network object for node in nodes: self.net.add_node(node) self.links = [] # Create links of the network self.l1 = Link(self.n1, self.n2) self.links.append(self.l1) self.l2 = Link(self.n2, self.n3) self.links.append(self.l2) self.l3 = Link(self.n3, self.n4) self.links.append(self.l3) self.l4 = Link(self.n3, self.n5) self.links.append(self.l4) self.l5 = Link(self.n5, self.n6) self.links.append(self.l5) self.l6 = Link(self.n6, self.n7) self.links.append(self.l6) self.l7 = Link(self.n4, self.n7) self.links.append(self.l7) self.l8 = Link(self.n7, self.n8) self.links.append(self.l8) # Add links to the network object for link in self.links: self.net.add_link(link) # Create spans of the links fibre_attenuation = 0.22 self.span_link1 = Span(length=45, fibre_attenuation=fibre_attenuation) self.span_link2 = Span(length=70, fibre_attenuation=fibre_attenuation) self.span_link5 = Span(length=45, fibre_attenuation=fibre_attenuation) self.span_link6 = Span(length=20, fibre_attenuation=fibre_attenuation) self.span_link7 = Span(length=25, fibre_attenuation=fibre_attenuation) # Add spans to the links self.net.add_span_to_link( self.l1, self.span_link1, Amplifier(target_gain=9.9, wavelength_dependent_gain_id='wdg1')) self.net.add_span_to_link( self.l2, self.span_link2, Amplifier(target_gain=15.4, wavelength_dependent_gain_id='wdg2')) self.net.add_span_to_link( self.l5, self.span_link5, Amplifier(target_gain=9.9, wavelength_dependent_gain_id='wdg2')) self.net.add_span_to_link( self.l6, self.span_link6, Amplifier(target_gain=4.4, wavelength_dependent_gain_id='wdg1')) self.net.add_span_to_link( self.l7, self.span_link7, Amplifier(target_gain=5.5, wavelength_dependent_gain_id='wdg2')) # Build network self.net.build() # Create a route to use for transmission route = [(self.n1, self.l1), (self.n2, self.l2), (self.n3, self.l4), (self.n5, self.l5), (self.n6, self.l6), (self.n7, self.l8), (self.n8, None)] # OpticalSignal index starts from 1 # Create OpticalSignal instances to sequencially add to transmission signals = [ OpticalSignal(81), OpticalSignal(82), OpticalSignal(83), OpticalSignal(84), OpticalSignal(85) ] # Invoke network function for transmission self.net.transmit(self.n1, self.n8, signals, route) if topo == 'linear': nodes = [] self.n1 = Node(1, amplifier=Amplifier(target_gain=9)) # Tx node nodes.append(self.n1) self.n2 = Node(2, amplifier=Amplifier(target_gain=9)) # in-line node nodes.append(self.n2) for node in nodes: self.net.add_node(node) links = [] self.l1 = Link(self.n1, self.n2) links.append(self.l1) for link in links: self.net.add_link(link) number_of_spans = link_length / span_length fibre_attenuation = 0.22 self.spans = [] while number_of_spans > 0: span = Span(length=span_length, fibre_attenuation=fibre_attenuation) self.net.add_span_to_link( self.l1, span, Amplifier(target_gain=span_length * fibre_attenuation, wavelength_dependent_gain_id='wdg1')) self.spans.append(span) number_of_spans -= 1 self.net.build() route = [(self.n1, self.l1), (self.n2, None)] # OpticalSignal index starts from 1 signals = [] for channel in channels: signals.append(OpticalSignal(channel)) self.net.transmit(self.n1, self.n2, signals, route)
def main(): args = parse_args() for spec in args.specid: spec_ind_twi = np.where(args.twi_df['Specid'] == spec)[0] for amp in config.Amps: amp_ind_twi = np.where(args.twi_df['Amp'] == amp)[0] twi_sel = np.intersect1d(spec_ind_twi, amp_ind_twi) for ind in twi_sel: if args.debug: print("Working on Cal for %s, %s" % (spec, amp)) twi1 = Amplifier(args.twi_df['Files'][ind], args.twi_df['Output'][ind], calpath=args.twi_df['Output'][ind], debug=True, refit=True, dark_mult=0.0, darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats < 1), init_lims=args.wvl_dict[amp], check_fibermodel=True, check_wave=True, fsize=args.fsize, fibmodel_nbins=args.fibmodel_bins, sigma=args.fibmodel_sig, power=args.fibmodel_pow) twi1.get_trace() fname = op.join( args.configdir, 'Fiber_Locations', args.twidir_date[0], 'fiber_loc_%s_%s_%s_%s.txt' % (args.twi_df['Specid'][ind], args.twi_df['Ifuslot'][ind], args.twi_df['Ifuid'][ind], amp)) if len(twi1.fibers) == args.nfibers[amp]: print("The correct number of fibers, %i, were found." % args.nfibers[amp]) Y = np.zeros((len(twi1.fibers), 2)) col = int(twi1.D * config.frac) for i, fiber in enumerate(twi1.fibers): Y[i, 0] = fiber.trace[col] print("Printing file for fibers.") create_fiber_file(fname, config.frac, Y) else: print("Only found %i fibers instead of the expected %i" % (len(twi1.fibers), args.nfibers[amp])) Y = find_missing_fibers(config.frac, twi1) create_fiber_file(fname, config.frac, Y) twi2 = Amplifier(args.twi_df['Files'][ind].replace( amp, config.Amp_dict[amp][0]), args.twi_df['Output'][ind], calpath=args.twi_df['Output'][ind], debug=True, refit=True, dark_mult=0.0, darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats < 1), init_lims=args.wvl_dict[amp], check_fibermodel=True, check_wave=True, fsize=args.fsize, fibmodel_nbins=args.fibmodel_bins, sigma=args.fibmodel_sig, power=args.fibmodel_pow) twi2.get_trace() folder = op.join(args.configdir, 'Fiber_Locations', args.twidir_date[0]) mkpath(folder) fname = op.join( args.configdir, 'Fiber_Locations', args.twidir_date[0], 'fiber_loc_%s_%s_%s_%s.txt' % (args.twi_df['Specid'][ind], args.twi_df['Ifuslot'][ind], args.twi_df['Ifuid'][ind], config.Amp_dict[amp][0])) if len(twi2.fibers) == args.nfibers[config.Amp_dict[amp][0]]: print("The correct number of fibers, %i, were found." % args.nfibers[config.Amp_dict[amp][0]]) Y = np.zeros((len(twi2.fibers), 2)) col = int(twi2.D * config.frac) for i, fiber in enumerate(twi2.fibers): Y[i, 0] = fiber.trace[col] print("Printing file for fibers.") create_fiber_file(fname, config.frac, Y) else: print("Only found %i fibers instead of the expected %i" % (len(twi2.fibers), args.nfibers[config.Amp_dict[amp][0]])) Y = find_missing_fibers(config.frac, twi2) create_fiber_file(fname, config.frac, Y)
def custom(args): lowfib = int(112 / 4. - 1.) midfib = int(112 / 2. - 1.) highfib = int(3.* 112. / 4. - 1.) trace_list = {"LL":[],"LU":[],"RU":[],"RL":[]} amps = {"LL":"LL","LU":"LL","RU":"RU","RL":"RU"} for spec in args.specid: spec_ind_twi = np.where(args.twi_df['Specid'] == spec)[0] spec_ind_sci = np.where(args.sci_df['Specid'] == spec)[0] for ind in spec_ind_twi: amp = args.twi_df['Amp'][ind] AMP = amps[amp] twi = Amplifier(args.twi_df['Files'][ind], args.twi_df['Output'][ind], calpath=args.twi_df['Output'][ind], debug=True, dark_mult=0.0, darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[AMP], use_pixelflat=(args.pixelflats<1), init_lims=args.wvl_dict[AMP], check_fibermodel=True, check_wave=True, fsize=args.fsize, fibmodel_nbins=args.fibmodel_bins, sigma=args.fibmodel_sig, power=args.fibmodel_pow, use_trace_ref=args.use_trace_ref) twi.load_fibers() if len(twi.fibers)==0: twi.get_trace() else: if not hasattr(twi.fibers[0],'trace'): twi.get_trace() blue = int(twi.D /4.) green = int(twi.D /2.) red = int(3.*twi.D /4.) trace_list[amp].append(np.array([twi.fibers[lowfib].trace[blue], twi.fibers[lowfib].trace[green], twi.fibers[lowfib].trace[red], twi.fibers[midfib].trace[blue], twi.fibers[midfib].trace[green], twi.fibers[midfib].trace[red], twi.fibers[highfib].trace[blue], twi.fibers[highfib].trace[green], twi.fibers[highfib].trace[red]])) for ind in spec_ind_sci: amp = args.sci_df['Amp'][ind] AMP = amps[amp] print(args.sci_df['Files'][ind]) sci = Amplifier(args.sci_df['Files'][ind], args.sci_df['Output'][ind], calpath=args.twi_dir, skypath=args.sky_dir, debug=False, refit=True, dark_mult=args.dark_mult[AMP], darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[AMP], use_pixelflat=(args.pixelflats<1), use_trace_ref=args.use_trace_ref, calculate_shift=False) sci.load_fibers() if len(sci.fibers)==0: sci.get_trace() else: if not hasattr(sci.fibers[0],'trace'): sci.get_trace() blue = int(sci.D /4.) green = int(sci.D /2.) red = int(3.*sci.D /4.) trace_list[amp].append(np.array([sci.fibers[lowfib].trace[blue], sci.fibers[lowfib].trace[green], sci.fibers[lowfib].trace[red], sci.fibers[midfib].trace[blue], sci.fibers[midfib].trace[green], sci.fibers[midfib].trace[red], sci.fibers[highfib].trace[blue], sci.fibers[highfib].trace[green], sci.fibers[highfib].trace[red]])) import matplotlib.pyplot as plt plt.figure(figsize=(12,12)) ax1 = plt.axes([0.1,0.1,0.35,0.35]) ax2 = plt.axes([0.1,0.55,0.35,0.35]) ax3 = plt.axes([0.55,0.1,0.35,0.35]) ax4 = plt.axes([0.55,0.55,0.35,0.35]) amps = ["LL","LU","RU","RL"] ax = [ax1,ax2,ax3,ax4] for i,amp in enumerate(amps): TR = np.array(trace_list[amp]) avg = biweight_location(TR,axis=(0,)) print(TR-avg) ax[i].plot(TR-avg) fn = op.join(args.output, args.scidir_date[0], args.instr, 'trace_%s.png' %args.specid[0]) plt.savefig(fn,dpi=150)
def reduce_twighlight(args): D = Distortion(op.join(args.configdir, 'DeformerDefaults', 'mastertrace_twi_027_L.dist')) for spec in args.specid: spec_ind_twi = np.where(args.twi_df['Specid'] == spec)[0] for amp in config.Amps: amp_ind_twi = np.where(args.twi_df['Amp'] == amp)[0] twi_sel = np.intersect1d(spec_ind_twi, amp_ind_twi) for ind in twi_sel: if args.debug: print("Working on Cal for %s, %s" %(spec, amp)) twi1 = Amplifier(args.twi_df['Files'][ind], args.twi_df['Output'][ind], calpath=args.twi_df['Output'][ind], debug=True, dark_mult=0.0, darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats<1), init_lims=args.wvl_dict[amp], check_fibermodel=True, check_wave=True, fsize=args.fsize, fibmodel_nbins=args.fibmodel_bins, sigma=args.fibmodel_sig, power=args.fibmodel_pow, use_trace_ref=args.use_trace_ref, default_fib = args.default_fib, wave_nbins = args.wave_nbins) #twi1.load_fibers() twi1.get_fiber_to_fiber() twi1.sky_subtraction() twi2 = Amplifier(args.twi_df['Files'][ind].replace(amp, config.Amp_dict[amp][0]), args.twi_df['Output'][ind], calpath=args.twi_df['Output'][ind], debug=True, dark_mult=0.0, darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats<1), init_lims=args.wvl_dict[amp], check_fibermodel=True, check_wave=True, fsize=args.fsize, fibmodel_nbins=args.fibmodel_bins, sigma=args.fibmodel_sig, power=args.fibmodel_pow, use_trace_ref=args.use_trace_ref, default_fib = args.default_fib, wave_nbins = args.wave_nbins) #twi2.load_fibers() twi2.get_fiber_to_fiber() twi2.sky_subtraction() image1 = get_model_image(twi1.image, twi1.fibers, 'fiber_to_fiber', debug=twi1.debug) image2 = get_model_image(twi2.image, twi2.fibers, 'fiber_to_fiber', debug=twi2.debug) outname = op.join(args.twi_df['Output'][ind], 'mastertrace_%s_%s.fits' %(args.twi_df['Specid'][ind], config.Amp_dict[amp][1])) make_spectrograph_image(image1, image2, twi1.header, outname) outname = op.join(args.twi_df['Output'][ind], 'mastertwi_%s_%s.fits' %(args.twi_df['Specid'][ind], config.Amp_dict[amp][1])) make_spectrograph_image(twi1.image, twi2.image, twi1.header, outname) outname = op.join(args.twi_df['Output'][ind], 'normtwi_%s_%s.fits' %(args.twi_df['Specid'][ind], amp)) make_amplifier_image(np.where( np.isfinite(twi1.skyframe)*(twi1.skyframe!=0), twi1.image/twi1.skyframe, 0.0), twi1.header, outname) outname = op.join(args.twi_df['Output'][ind], 'normtwi_%s_%s.fits' %(args.twi_df['Specid'][ind], config.Amp_dict[amp][0])) make_amplifier_image(np.where( np.isfinite(twi2.skyframe)*(twi2.skyframe!=0), twi2.image/twi2.skyframe, 0.0), twi2.header, outname) D = recalculate_dist_coeff(D, twi1, twi2) outname2 = op.join(args.twi_df['Output'][ind], 'mastertrace_%s_%s.dist' %(args.twi_df['Specid'][ind], config.Amp_dict[amp][1])) D.writeto(outname2) twi1.save_fibers() twi2.save_fibers() if args.debug: print("Finished working on Cal for %s, %s" %(spec, amp))
sys.path.append('/Users/dmiller/aoc') from amplifier import Amplifier from itertools import permutations file = open('input.txt') initial_data = list(map(int, file.read().split(','))) #initial_data = [3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0] #initial_data = [3,23,3,24,1002,24,10,24,1002,23,-1,23,101,5,23,23,1,24,23,23,4,23,99,0,0] phase_permutations = permutations(range(5), 5) print('Starting Part 1 diagnostics') max_thrust = 0 for phases in phase_permutations: ampA = Amplifier(initial_data) ampA.set_phase(phases[0]) ampA.set_input(0) ampA.run() ampB = Amplifier(initial_data) ampB.set_phase(phases[1]) ampB.set_input(ampA.get_output()) ampB.run() ampC = Amplifier(initial_data) ampC.set_phase(phases[2]) ampC.set_input(ampB.get_output()) ampC.run() ampD = Amplifier(initial_data) ampD.set_phase(phases[3]) ampD.set_input(ampC.get_output()) ampD.run()
def __init__(self, program, phase_settings, feedback_loop_mode=False): self.amplifiers = [ Amplifier(program, setting) for setting in phase_settings ] self.feedback_loop_mode = feedback_loop_mode
def __init__(self): # Create a Network object self.net = Network() nodes = [] # Create the nodes of the network n1 = Node(1, amplifier=Amplifier(target_gain=9)) nodes.append(n1) n2 = Node(2, amplifier=Amplifier(target_gain=9)) nodes.append(n2) n3 = Node(3) nodes.append(n3) n4 = Node(4, amplifier=Amplifier(target_gain=18)) nodes.append(n4) n5 = Node(5, amplifier=Amplifier(target_gain=18)) nodes.append(n5) n6 = Node(6, amplifier=Amplifier(target_gain=9)) nodes.append(n6) n7 = Node(7) nodes.append(n7) n8 = Node(8) nodes.append(n8) for node in nodes: self.net.add_node(node) links = [] # Create links of the network l1 = Link(n1, n2) links.append(l1) l2 = Link(n2, n3) links.append(l2) l3 = Link(n3, n4) links.append(l3) l4 = Link(n3, n5) links.append(l4) l5 = Link(n5, n6) links.append(l5) l6 = Link(n6, n7) links.append(l6) l7 = Link(n4, n7) links.append(l7) l8 = Link(n7, n8) links.append(l8) for link in links: self.net.add_link(link) # Create spans of the links fibre_attenuation = 0.2 span_link1 = Span(length=45, fibre_attenuation=fibre_attenuation) span_link2 = Span(length=70, fibre_attenuation=fibre_attenuation) span_link5 = Span(length=45, fibre_attenuation=fibre_attenuation) span_link6 = Span(length=20, fibre_attenuation=fibre_attenuation) span_link7 = Span(length=25, fibre_attenuation=fibre_attenuation) # Add spans to the links self.net.add_span_to_link( l1, span_link1, Amplifier(target_gain=9, wavelength_dependent_gain_id='wdg1')) self.net.add_span_to_link( l2, span_link2, Amplifier(target_gain=14, wavelength_dependent_gain_id='wdg1')) self.net.add_span_to_link( l5, span_link5, Amplifier(target_gain=9, wavelength_dependent_gain_id='wdg1')) self.net.add_span_to_link( l6, span_link6, Amplifier(target_gain=4, wavelength_dependent_gain_id='wdg1')) self.net.add_span_to_link( l7, span_link7, Amplifier(target_gain=5, wavelength_dependent_gain_id='wdg1')) self.net.build() route = [(n1, l1), (n2, l2), (n3, l4), (n5, l5), (n6, l6), (n7, l8), (n8, None)] # OpticalSignal index starts from 1 signals = [ OpticalSignal(83), OpticalSignal(81), OpticalSignal(82), OpticalSignal(84), OpticalSignal(85) ] self.net.transmit(n1, n8, signals, route) channel = 1529.2 + 83 * 0.4 osnr_values = [] spans_length = [] osnr_values.append( abs_to_db((10**(-2.0 / 10.0) * 0.8 - (10**(-39.0 / 10.0) * 4)) / (10**(-39.0 / 10.0)))) # print(abs_to_db((10**(-2.0/10.0)*0.8-(10**(-39.0/10.0)*4))/(10**(-39.0/10.0)))) spans_length.append(0) osnr = self.net.monitor(l1, span_link1, 83, links) # print("OSNR of channel %s (nm) is %s dB at span %s." % ( # str(channel), str(osnr), span_link1.span_id)) osnr_values.append(osnr) spans_length.append(span_link1.length) osnr = self.net.monitor(l2, span_link2, 83, links) # print("OSNR of channel %s (nm) is %s dB at span %s." % ( # str(channel), str(osnr), span_link2.span_id)) osnr_values.append(osnr) spans_length.append(span_link2.length) osnr = self.net.monitor(l5, span_link5, 83, links) # print("OSNR of channel %s (nm) is %s dB at span %s." % ( # str(channel), str(osnr), span_link5.span_id)) osnr_values.append(osnr) spans_length.append(span_link5.length) osnr = self.net.monitor(l6, span_link6, 83, links) # print("OSNR of channel %s (nm) is %s dB at span %s." % ( # str(channel), str(osnr), span_link6.span_id)) osnr_values.append(osnr) spans_length.append(span_link6.length) graphics = Graphic() graphics.plot_osnr_increment(osnr_values, spans_length)
def amp_wrapper(prog): highest = -np.inf best = None exited = [False] * 5 amp_A = Amplifier("A", prog.copy(), [].copy()) amp_B = Amplifier("B", prog.copy(), [].copy()) amp_C = Amplifier("C", prog.copy(), [].copy()) amp_D = Amplifier("D", prog.copy(), [].copy()) amp_E = Amplifier("E", prog.copy(), [].copy()) for phase in list(itertools.permutations(list(range(5, 10)))): [a, b, c, d, e] = phase amp_A.inputs.append(a) amp_B.inputs.append(b) amp_C.inputs.append(c) amp_D.inputs.append(d) amp_E.inputs.append(e) exited = [False] * 5 e_out = 0 # initial input loopcount = 0 # debug(f"\nPhase input: {phase}\n") while (True): amp_A.inputs.append(e_out) amp_A.run_prog_from_current_state() a_out = amp_A.outputs[-1] amp_B.inputs.append(a_out) amp_B.run_prog_from_current_state() b_out = amp_B.outputs[-1] amp_C.inputs.append(b_out) amp_C.run_prog_from_current_state() c_out = amp_C.outputs[-1] amp_D.inputs.append(c_out) amp_D.run_prog_from_current_state() d_out = amp_D.outputs[-1] amp_E.inputs.append(d_out) amp_E.run_prog_from_current_state() e_out = amp_E.outputs[-1] if amp_E.has_exited: break thruster_signal = e_out if highest < thruster_signal: highest = thruster_signal best_phases = [a, b, c, d, e].copy() amp_A.reset() amp_B.reset() amp_C.reset() amp_D.reset() amp_E.reset() print("BEST PHASES: " + str(best_phases)) print("HIGHEST THRUSTER SIGNAL: " + str(highest))
def reduce_science(args): for spec in args.specid: spec_ind_sci = np.where(args.sci_df['Specid'] == spec)[0] for amp in config.Amps: amp_ind_sci = np.where(args.sci_df['Amp'] == amp)[0] sci_sel = np.intersect1d(spec_ind_sci, amp_ind_sci) for ind in sci_sel: if args.instr == "virus": if not args.use_trace_ref: ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', args.ifucen_fn[amp][0] + args.sci_df['Ifuid'][ind] + '.txt'), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) else: if args.sci_df['Ifuid'][ind] == '004': ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', 'IFUcen_HETDEX_reverse_R.txt'), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) ifucen[224:,:] = ifucen[-1:223:-1,:] else: ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', 'IFUcen_HETDEX.txt'), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) else: ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', args.ifucen_fn[amp][0]), usecols=[0,1,2], skiprows=args.ifucen_fn[amp][1]) if args.debug: print("Working on Sci for %s, %s" %(spec, amp)) if args.check_if_twi_exists: fn = op.join(args.twi_dir,'fiber_*_%s_%s_%s_%s.pkl' %(spec, args.sci_df['Ifuslot'][ind], args.sci_df['Ifuid'][ind], amp)) calfiles = glob.glob(fn) if not calfiles: print("No cals found for %s,%s: %s" %(spec, amp, args.sci_df['Files'][ind])) print("If you want to produce cals include " "--reduce_twi") sci1 = Amplifier(args.sci_df['Files'][ind], args.sci_df['Output'][ind], calpath=args.twi_dir, skypath=args.sky_dir, debug=False, refit=False, dark_mult=args.dark_mult[amp], darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats<1), use_trace_ref=args.use_trace_ref, calculate_shift=args.adjust_trace, fiber_date=args.fiber_date, cont_smooth=args.cont_smooth) #sci1.load_fibers() #if sci1.fibers and not args.start_from_scratch: # if sci1.fibers[0].spectrum is not None: # sci1.prepare_image() # sci1.sky_subtraction() # sci1.clean_cosmics() #else: sci1.load_all_cal() if args.adjust_trace: sci1.refit=True sci1.get_trace() sci1.refit=False sci1.fiberextract() if args.refit_fiber_to_fiber: sci1.refit=True sci1.get_fiber_to_fiber() sci1.refit=False sci1.sky_subtraction() sci1.clean_cosmics() sci1.fiberextract() sci1.sky_subtraction() sci2 = Amplifier(args.sci_df['Files'][ind].replace(amp, config.Amp_dict[amp][0]), args.sci_df['Output'][ind], calpath=args.twi_dir, skypath=args.sky_dir, debug=False, refit=False, dark_mult=args.dark_mult[config.Amp_dict[amp][0]], darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats<1), use_trace_ref=args.use_trace_ref, calculate_shift=args.adjust_trace, fiber_date=args.fiber_date, cont_smooth=args.cont_smooth) #sci2.load_fibers() #if sci2.fibers and not args.start_from_scratch: # if sci2.fibers[0].spectrum is not None: # sci2.prepare_image() # sci2.sky_subtraction() # sci2.clean_cosmics() #else: sci2.load_all_cal() if args.adjust_trace: sci2.refit=True sci2.get_trace() sci2.refit=False sci2.fiberextract() if args.refit_fiber_to_fiber: sci2.refit=True sci2.get_fiber_to_fiber() sci2.refit=False sci2.sky_subtraction() sci2.clean_cosmics() sci2.fiberextract() sci2.sky_subtraction() outname = op.join(args.sci_df['Output'][ind], 'S%s_%s_sci_%s.fits' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_spectrograph_image(sci1.clean_image, sci2.clean_image, sci1.header, outname) make_spectrograph_image(sci1.error, sci2.error, sci1.header, op.join(op.dirname(outname), 'ee.'+op.basename(outname))) make_error_frame(sci1.clean_image, sci2.clean_image, sci1.mask, sci2.mask, sci1.header, outname) outname = op.join(args.sci_df['Output'][ind], 'cS%s_%s_sci_%s.fits' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_spectrograph_image(np.where(sci1.mask==0, sci1.clean_image, 0.0), np.where(sci2.mask==0, sci2.clean_image, 0.0), sci1.header, outname) make_error_frame(sci1.clean_image, sci2.clean_image, sci1.mask, sci2.mask, sci1.header, outname) outname = op.join(args.sci_df['Output'][ind], 'CsS%s_%s_sci_%s.fits' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_spectrograph_image(sci1.continuum_sub, sci2.continuum_sub, sci1.header, outname) make_error_frame(sci1.continuum_sub, sci2.continuum_sub, sci1.mask, sci2.mask, sci1.header, outname) outname = op.join(args.sci_df['Output'][ind], 'cCsS%s_%s_sci_%s.fits' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_spectrograph_image(np.where(sci1.mask==0, sci1.continuum_sub, 0.0), np.where(sci2.mask==0, sci2.continuum_sub, 0.0), sci1.header, outname) make_error_frame(sci1.continuum_sub, sci2.continuum_sub, sci1.mask, sci2.mask, sci1.header, outname) outname = op.join(args.sci_df['Output'][ind], 'cCsS%s_%s_sci_%s_imstat.png' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) imstat(sci1.residual, sci2.residual, sci1.fibers, sci2.fibers, outname) Fe, FeS = recreate_fiberextract(sci1, sci2, wavelim=args.wvl_dict[amp], disp=args.disp[amp]) outname = op.join(args.sci_df['Output'][ind], 'Fe%s_%s_sci_%s.fits' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_fiber_image(Fe, sci1.header, outname, args, amp) make_fiber_error(Fe, sci1.header, outname, args, amp) make_cube_file(args, outname, ifucen, args.cube_scale, config.Amp_dict[amp][1]) outname = op.join(args.sci_df['Output'][ind], 'FeS%s_%s_sci_%s.fits' %( op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_fiber_image(FeS, sci1.header, outname, args, amp) make_fiber_error(FeS, sci1.header, outname, args, amp) make_cube_file(args, outname, ifucen, args.cube_scale, config.Amp_dict[amp][1]) if args.save_sci_fibers: sci1.save_fibers() sci2.save_fibers() if args.save_sci_amplifier: sci1.save() sci2.save() if args.debug: print("Finished working on Sci for %s, %s" %(spec, amp))
def reduce_science(args): for spec in args.specid: spec_ind_sci = np.where(args.sci_df['Specid'] == spec)[0] for amp in config.Amps: amp_ind_sci = np.where(args.sci_df['Amp'] == amp)[0] sci_sel = np.intersect1d(spec_ind_sci, amp_ind_sci) for ind in sci_sel: if args.instr == "virus": if not args.use_trace_ref: ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', args.ifucen_fn[amp][0] + args.sci_df['Ifuid'][ind] + '.txt'), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) else: if args.sci_df['Ifuid'][ind] == '004': ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', 'IFUcen_HETDEX_reverse_R.txt'), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) ifucen[224:,:] = ifucen[-1:223:-1,:] else: ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', 'IFUcen_HETDEX.txt'), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) else: ifucen = np.loadtxt(op.join(args.configdir, 'IFUcen_files', args.ifucen_fn[amp][0]), usecols=[0,1,2,4], skiprows=args.ifucen_fn[amp][1]) if args.debug: print("Working on Sci/Twi for %s, %s" %(spec, amp)) if args.check_if_twi_exists: fn = op.join(args.twi_dir,'fiber_*_%s_%s_%s_%s.pkl' %(spec, args.sci_df['Ifuslot'][ind], args.sci_df['Ifuid'][ind], amp)) calfiles = glob.glob(fn) if not calfiles: print("No cals found for %s,%s: %s" %(spec, amp, args.sci_df['Files'][ind])) print("If you want to produce cals include " "--reduce_twi") sci1 = Amplifier(args.sci_df['Files'][ind], args.sci_df['Output'][ind], calpath=args.twi_dir, skypath=args.sky_dir, debug=False, refit=False, dark_mult=args.dark_mult[amp], darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats<1), use_trace_ref=args.use_trace_ref, calculate_shift=args.adjust_trace, fiber_date=args.fiber_date, cont_smooth=args.cont_smooth, make_residual=False, do_cont_sub=False, make_skyframe=False) sci1.load_all_cal() wavelim=[4500,4600] xlim = np.interp([wavelim[0],wavelim[1]], np.linspace(args.wvl_dict[amp][0], args.wvl_dict[amp][1], sci1.D), np.arange(sci1.D)) cols=np.arange(int(xlim[0])-10,int(xlim[1])+10) sci1.fiberextract(cols=cols) sci1.sky_subtraction() sci2 = Amplifier(args.sci_df['Files'][ind].replace(amp, config.Amp_dict[amp][0]), args.sci_df['Output'][ind], calpath=args.twi_dir, skypath=args.sky_dir, debug=False, refit=False, dark_mult=args.dark_mult[config.Amp_dict[amp][0]], darkpath=args.darkdir, biaspath=args.biasdir, virusconfig=args.configdir, specname=args.specname[amp], use_pixelflat=(args.pixelflats<1), use_trace_ref=args.use_trace_ref, calculate_shift=args.adjust_trace, fiber_date=args.fiber_date, cont_smooth=args.cont_smooth, make_residual=False, do_cont_sub=False, make_skyframe=False) sci2.load_all_cal() sci2.fiberextract(cols=cols) sci2.sky_subtraction() Fe, FeS = recreate_fiberextract(sci1, sci2, wavelim=wavelim, disp=args.disp[amp]) FE = [Fe, FeS] FEN = ['Fe', 'FeS'] for f,n in zip(FE, FEN): outname = op.join(args.sci_df['Output'][ind], '%s%s_%s_sci_%s.fits' %(n, op.basename(args.sci_df['Files'][ind]).split('_')[0], args.sci_df['Ifuslot'][ind], config.Amp_dict[amp][1])) make_fiber_image(f, sci1.header, outname, args, amp) make_cube_file(args, outname, ifucen, args.cube_scale, config.Amp_dict[amp][1]) if args.save_sci_fibers: sci1.save_fibers() sci2.save_fibers() if args.save_sci_amplifier: sci1.save() sci2.save() if args.debug: print("Finished working on Sci/Twi for %s, %s" %(spec, amp))
from amplifier import Amplifier input = list(map(int, open("2019/9/input.txt", "r").read().split(","))) # input = [104,1125899906842624,99] amplifier = Amplifier(input) amplifier.run_int_code([1])