Esempio n. 1
0
    def get_alpha_G(self, K):
        robot_ids = Set([e.id for e in self.robots])
        task_ids = Set([e.id for e in self.tasks])
        V = Set.descartes_product(robot_ids, task_ids)
        V_K = Set([Set(e) for e in itertools.combinations(V, K)])
        S_K = self.history
        S_K_1 = Set(self.history[:-1])

        print("...Calculating alpha_G...")
        alpha_G = -float('inf')
        N = len(V_K)
        progress_bar = ProgressBar(N)
        instrument = Instrument()
        instrument.start()
        k = 0
        for Omega in V_K:
            progress_bar.progress(k)
            k = k + 1
            for j_i in S_K_1.setminus(Omega):
                i = S_K.index(j_i)
                S_i_1 = Allocation(self.history[0:i])
                lhs = Allocation(S_i_1.union(Omega)).get_derivative(Set([j_i]))
                rhs = S_i_1.get_derivative(Set([j_i]))
                frac = (lhs - rhs) / lhs
                if frac > alpha_G and rhs != 0 and lhs != 0:
                    alpha_G = frac
        progress_bar.progress(N, 'Finished!\n')
        calculation_time = instrument.stop()
        print("Calculation time [s]:", calculation_time)
        print("Finished calculating alpha_G!\n")
        return alpha_G
Esempio n. 2
0
    def update(self, *args):
        """Updates the graph with the altered sliders"""
        #Fetches slider information
        s1 = self.s1.get()
        s2 = self.s2.get()
        r1 = self.r1.get()
        r2 = self.r2.get()
        p = self.p.get()

        #Changes the number next to the bar
        self.r1_string.configure(text="%.2f" % r1)
        self.r2_string.configure(text="%.2f" % r2)
        self.s1_string.configure(text="%.2f" % s1)
        self.s2_string.configure(text="%.2f" % s2)
        self.p_string.configure(text="%.2f" % self.p.get())

        #Creates two asset objects
        self.I1 = Instrument(r1, s1, "Asset 1", "Equity")
        self.I2 = Instrument(r2, s2, "Asset 2", "Bond")

        #Builds a portfolio object
        self.port = Portfolio([self.I1, self.I2])
        self.port.addcorr([[0, p]])

        #Displays the new graph to the graph frame
        fff = Frame(height=400, width=400, bd=10, bg='white')
        Chart(self.port, 0.02).scatter(fff)
        fff.grid(row=1, column=0)
Esempio n. 3
0
    def get_gamma_G(self, K):
        robot_ids = Set([e.id for e in self.robots])
        task_ids = Set([e.id for e in self.tasks])
        V = Set.descartes_product(robot_ids, task_ids)
        V_K = Set([Set(e) for e in itertools.combinations(V, K)])

        print("...Calculating gamma_G...")
        gamma_G = float('inf')
        N = len(self.history) * len(V_K)
        progress_bar = ProgressBar(N)
        instrument = Instrument()
        instrument.start()
        k = 0
        for t in range(len(self.history)):
            S_t = Allocation(self.history[0:t])
            for Omega in V_K:
                progress_bar.progress(k)
                k = k + 1
                lhs = 0
                for omega in Omega.setminus(Set(S_t)):
                    lhs = lhs + S_t.get_derivative(Set([omega]))
                rhs = S_t.get_derivative(Omega)
                frac = rhs / lhs
                if frac < gamma_G and rhs != 0 and lhs != 0:
                    gamma_G = frac
        progress_bar.progress(N, 'Finished!\n')
        calculation_time = instrument.stop()
        print("Calculation time [s]:", calculation_time)
        print("Finished calculating gamma_G!\n")
        return gamma_G
Esempio n. 4
0
def get_instrument_config_file(development):
    config = configparser.ConfigParser()
    config.read(config_file)
    instrument = Instrument(
        mqtt_org=eval(config['MQTT_SETTINGS']['MQTT_ORG']),
        mqtt_host=eval(config['MQTT_SETTINGS']['MQTT_SERVER']),
        mqtt_port=eval(config['MQTT_SETTINGS']['MQTT_PORT']),
        mqtt_keep_alive=eval(config['MQTT_SETTINGS']['MQTT_KEEPALIVE']),
        mqtt_qos=eval(config['MQTT_SETTINGS']['MQTT_QOS']),
        serial_port_description=eval(
            config['SERIAL_SETTINGS']['SERIAL_PORT_DESCRIPTION']),
        serial_baudrate=eval(config['SERIAL_SETTINGS']['SERIAL_BAUDRATE']),
        serial_parity=eval(config['SERIAL_SETTINGS']['SERIAL_PARITY']),
        serial_stopbits=eval(config['SERIAL_SETTINGS']['SERIAL_STOPBITS']),
        serial_bytesize=eval(config['SERIAL_SETTINGS']['SERIAL_BYTESIZE']),
        serial_timeout=eval(config['SERIAL_SETTINGS']['SERIAL_TIMEOUT']),
        storage_location=eval(config['GENERAL_SETTINGS']['STORAGE_LOCATION']),

        # Test serial emulator
        serial_emulator=development)
    if (development):
        from SerialEmulator import SerialEmulator
        ser = SerialEmulator()
        instrument._serial = ser
    set_options_config_file(config, instrument)
    return instrument
Esempio n. 5
0
	def __init__(self, params):
		if 'let_ring' not in params:
			params["let_ring"] = True
		if 'channel' not in params:
			params["channel"] = 1
		if 'midi_instr' not in params:
			params["midi_instr"] = randrange(1, 9)
		Instrument.__init__(self, params)
Esempio n. 6
0
 def get_all_function_values(self, target_allocation):
     targets = []
     for a in target_allocation:
         targets = targets + [a.target]
     goal = self.robots[0].goal
     x_0 = [r.x_0 for r in self.robots]
     instrument = Instrument()
     instrument.start()
     V_ret, Mu, V = self.path_planner.get_solution(targets, goal, x_0)
     t_eval = instrument.stop()
     return V_ret, Mu, V, t_eval
Esempio n. 7
0
 def test_convexity(self):
     r = 0.0500
     d = []
     cf = []
     i = 0
     while (i < 10):
         d.append(FixedIncome.discount(spot=r, nper=i + 1))
         cf.append(4)
         i += 1
     cf[len(cf) - 1] += 100
     my_instrument = Instrument(discounts=d, cash_flows=cf, ppy=2)
     self.assertEqual(round(my_instrument.convexity(), 2), 19.57)
Esempio n. 8
0
 def test_modified_duration(self):
     r = 0.0500
     d = []
     cf = []
     i = 0
     while (i < 10):
         d.append(FixedIncome.discount(spot=r, nper=i + 1))
         cf.append(7)
         i += 1
     cf[len(cf) - 1] += 100
     my_instrument = Instrument(discounts=d, cash_flows=cf, ppy=2)
     self.assertEqual(round(my_instrument.modified_duration(), 2), 3.67)
Esempio n. 9
0
File: TM.py Progetto: zkbt/transit
	def load(self, directory):
		'''Load parameters from directory.'''
		#self.directory = directory
		self.speak('loading TM from {0}'.format(directory))
		self.planet = Planet(directory=directory)
		self.star = Star(directory=directory)
		self.instrument = Instrument(directory=directory)
Esempio n. 10
0
 def __init__(self, function_frame):
     Allocation.set_up(function_frame)
     self.function_frame = function_frame
     self.path_planner = function_frame.path_planner
     self.robots = copy.deepcopy(function_frame.robots)
     self.tasks = copy.deepcopy(function_frame.tasks)
     self.instrument = Instrument()
Esempio n. 11
0
def get_instrument(instrument_name):
    ins = Instrument(instrument_name.replace(" ", ""))
    if ins is None:
        print(f'Error while fetching instrument {instrument_name}')
        return -1
    if ins.token == -1:
        return -1
    return ins
Esempio n. 12
0
    def calculating_function_frame(self):
        print("Calculating function frame...")
        self.instrument = Instrument()
        self.instrument.start()

        task_subsets = []
        for i in range(len(self.tasks) + 1):
            task_subsets = task_subsets + [
                Set(list(e)) for e in itertools.combinations(self.tasks, i)
            ]
        task_subsets = Set(task_subsets)

        domain_robots = [e.id for e in self.robots]
        domain_tasks = [set([ee.id for ee in e]) for e in task_subsets]
        self.domain_dict = ["value", "time"]
        self.domain_matrix = [domain_robots, domain_tasks]
        self["value"] = Matrix(
            self.domain_matrix,
            np.zeros((len(domain_robots), len(domain_tasks))))
        self["time"] = Matrix(
            self.domain_matrix,
            np.zeros((len(domain_robots), len(domain_tasks))))

        N = len(task_subsets)
        progress_bar = ProgressBar(N)
        for i_allocation, target_allocation in enumerate(task_subsets):
            progress_bar.progress(i_allocation)
            V_ret, Mu, V, t_eval = self.get_all_function_values(
                target_allocation)
            #save Mu and V ???
            self["value"].matrix[:, i_allocation] = V_ret
            self["time"].matrix[:, i_allocation] = t_eval * np.ones(len(V_ret))
        progress_bar.progress(N, 'Finished!\n')
        calculation_time = self.instrument.stop()
        self.instrument.save_measurement("calculation_time", calculation_time)
        print("Calculation time [s]:")
        print(self.instrument.data)
        print("Finished calculating function frame!\n")
Esempio n. 13
0
def main():
    """Defines assets, creates portfolios, and displays a scatter plot 
    of the different portfolios"""
    s1 = Instrument(0.01, 0.01, "Asset 1", "Equity")
    s2 = Instrument(0.02, 0.02, "Asset 2", "Bond")
    s3 = Instrument(0.03, 0.03, "Asset 3", "Commodity")
    s4 = Instrument(0.04, 0.04, "Asset 4", "Equity")

    p1 = Portfolio([s1, s2])
    p2 = Portfolio([s1, s3])
    p3 = Portfolio([s1, s4])
    p4 = Portfolio([s2, s3])
    p5 = Portfolio([s2, s4])
    p6 = Portfolio([s3, s4])

    p1.addcorr([[0, -0.1]])
    p2.addcorr([[0, -0.1]])
    p3.addcorr([[0, -0.1]])
    p4.addcorr([[0, -0.1]])
    p5.addcorr([[0, -0.1]])
    p6.addcorr([[0, -0.1]])

    c = Chart([p1, p2, p3, p4, p5, p6], 0.004)
    c.scatters(size=3)
 def createInstrumentList(self):
     f = open('initialRandomValues.txt', 'r')
     instrumentId = 1000
     instrumentList = []
     for instrumentName in instruments:
         hashedValue = int(f.readline())
         isNegative = hashedValue < 0
         basePrice = (abs(hashedValue) % 10000) + 90.0
         drift = ((abs(hashedValue) % 5) * basePrice) / 1000.0
         drift = 0 - drift if isNegative else drift
         variance = (abs(hashedValue) % 1000) / 100.0
         variance = 0 - variance if isNegative else variance
         instrument = Instrument(instrumentId, instrumentName, basePrice,
                                 drift, variance)
         instrumentList.append(instrument)
         instrumentId += 1
     return instrumentList
Esempio n. 15
0
def main():
    '''
    Generats world along with note blocks.
    **Parameters**
    --------------
    **Notes**
    '''
    # More interesting generator string: "3;7,44*49,73,35:1,159:4,95:13,35:13,159:11,95:10,159:14,159:6,35:6,95:6;12;"
    piano = Instrument()
    missionXML = genString(piano)

    # Create default Malmo objects:
    agent_host = MalmoPython.AgentHost()
    try:
        agent_host.parse( sys.argv )
    except RuntimeError as e:
        print('ERROR:',e)
        print(agent_host.getUsage())
        exit(1)
    if agent_host.receivedArgument("help"):
        print(agent_host.getUsage())
        exit(0)

    my_mission = MalmoPython.MissionSpec(missionXML, True)
    my_mission_record = MalmoPython.MissionRecordSpec()
    my_mission_video = my_mission.requestVideo(800,500)

    # 1 - Attempt to start a mission:
    max_retries = 3
    startTheMission(agent_host, my_mission, my_mission_record, max_retries)

    # 2 - Loop until mission starts:
    print("Waiting for the mission to start ", end=' ')
    world_state = agent_host.getWorldState()
    world_state = waitingForMissionStart(world_state, agent_host)
    print("\nMission running ", end=' ')

    # 3 - Loop until mission ends:
    world_state = runMission(world_state, agent_host, piano)
    print("\nMission ended")
Esempio n. 16
0
            sys.exit(1)
    else:
        frameint = None

    # Specified a status server for the instrument to use to fetch
    # status (not via the DAQtk status mechanism)
    if options.statushost:
        statusObj = cachedStatusObj(options.statushost)

    else:
        statusObj = None

    # Create the instrument object
    simcam = Instrument(logger, ev_quit=ev_quit, 
                        ocsint=daqtk, frameint=frameint,
                        statusObj=statusObj, obcpnum=options.obcpnum,
                        threadPool=threadPool,
                        allowNoPara=options.noparaok)

    # Load the personalities.  User can specify several cams to be loaded
    # on the command line.  Also, cams can be given aliases.
    for (alias, cam) in camlist:
        simcam.loadPersonality(cam, alias=alias)

    # Load the paradirs
    if len(paradirs) > 0:
        simcam.loadParaDirs(paradirs)
        
    try:
        try:
            logger.debug("Starting threadPool ...")
Esempio n. 17
0
 def __init__(self, resource, mode = "SERIAL", baud=9600):
     Instrument.__init__(self, resource, mode, baud)
     self.vmax = [32, 32, 6]
     self.imax = [2, 2, 5]
     self.channels = [1,2,3]
Esempio n. 18
0
 def __init__(self, params):
     if "midi_instr" not in params:
         params["midi_instr"] = randrange(33, 40)
     Instrument.__init__(self, params)
Esempio n. 19
0
File: TM.py Progetto: zkbt/transit
class TM(Talker):
	'''Transit Model object handles generation of model transit light curves.
		(relies heavily on Jonathan Irwin's "eb" code, which is an updated
		implementation of the classic EBOP and JKTEBOP, available at:
			https://github.com/mdwarfgeek'''

	def __init__(self, planet=None, star=None, instrument=None, directory=None,depthassumedforplotting=None, **kwargs):
		'''Initialize the parameters of the model.'''

		# setup the talker
		Talker.__init__(self)

		# create an empty array of parameters for eb
		self.ebparams = np.zeros(eb.NPAR, dtype=np.double)

		# keep track of a depth for plotting, if necessary
		self.depthassumedforplotting=depthassumedforplotting


		# load the model, if possible, and if a directory was given
		self.directory = directory
		if directory is not None and planet is None:
			self.load(directory)
		else:
			# define the subsets of the parameters, maybe by falling to defaults
			if planet is None:
				planet = Planet()
			if star is None:
				star = Star()
			if instrument is None:
				instrument = Instrument()
			self.planet = planet
			self.star = star
			self.instrument = instrument


	def load(self, directory):
		'''Load parameters from directory.'''
		#self.directory = directory
		self.speak('loading TM from {0}'.format(directory))
		self.planet = Planet(directory=directory)
		self.star = Star(directory=directory)
		self.instrument = Instrument(directory=directory)

	def save(self, directory):
		'''Save parameters to directory.'''
		#self.directory = directory
		for x in (self.planet, self.star, self.instrument):
			x.save(directory)

	def linkLightCurve(self, transitlightcurve):
		'''Attach a model to a light curve, defining all the TM and TLC attributes.'''
		self.TLC = transitlightcurve
		self.TM = self
		self.TLC.TM = self
		self.TLC.TLC = self.TLC

	def linkRV(self, rvcurve):
		'''Attach a model to a radial velocity curve, defining all the TM and RVC attributes.'''
		self.RVC = rvcurve
		self.TM = self
		self.RVC.TM  = self
		self.RVC.RVC = self.RVC

	#@profile
	def set_ebparams(self):
		'''Set up the parameters required for eb. '''
		# These are the basic parameters of the model.
		self.ebparams[eb.PAR_J]      =  self.planet.surface_brightness_ratio  # J surface brightness ratio
		self.ebparams[eb.PAR_RASUM]  =  self.planet.rsum_over_a  # (R_1+R_2)/a
		self.ebparams[eb.PAR_RR]     =  self.planet.rp_over_rs  # R_2/R_1
		self.ebparams[eb.PAR_COSI]   =  self.planet.cosi  # cos i

		# Mass ratio is used only for computing ellipsoidal variation and
		# light travel time.  Set to zero to disable ellipsoidal.
		self.ebparams[eb.PAR_Q]      =  0#self.planet.q

		# Light travel time coefficient.
		#ktot = 55.602793  # K_1+K_2 in km/s
		#cltt = 1000*ktot / eb.LIGHT

		# Set to zero if you don't need light travel correction (it's fairly slow
		# and can often be neglected).
		self.ebparams[eb.PAR_CLTT]   =  0#cltt#*(self.planet.q.value == 0.0)      # ktot / c

		# Radiative properties of star 1.
		self.ebparams[eb.PAR_LDLIN1] = self.star.u1.value   # u1 star 1
		self.ebparams[eb.PAR_LDNON1] = self.star.u2.value  # u2 star 1
		self.ebparams[eb.PAR_GD1]    = self.star.gd.value     # gravity darkening, std. value
		self.ebparams[eb.PAR_REFL1]  = self.star.albedo.value      # albedo, std. value

		# Spot model.  Assumes spots on star 1 and not eclipsed.
		self.ebparams[eb.PAR_ROT1]   =  1.0# 0.636539  # rotation parameter (1 = sync.)
		self.ebparams[eb.PAR_FSPOT1] =  0.0       # fraction of spots eclipsed
		self.ebparams[eb.PAR_OOE1O]  =  0.0       # base spottedness out of eclipse
		self.ebparams[eb.PAR_OOE11A] =  0.0#0.006928  # *sin
		self.ebparams[eb.PAR_OOE11B] =  0.0 # *cos

		# PAR_OOE12* are sin(2*rot*omega) on star 1,
		# PAR_OOE2* are for spots on star 2.

		# Assume star 2 is the same as star 1 but without spots.
		self.ebparams[eb.PAR_LDLIN2] = self.ebparams[eb.PAR_LDLIN1]
		self.ebparams[eb.PAR_LDNON2] = self.ebparams[eb.PAR_LDNON1]
		self.ebparams[eb.PAR_GD2]    = self.ebparams[eb.PAR_GD1]
		self.ebparams[eb.PAR_REFL2]  = self.ebparams[eb.PAR_REFL1]

		# Orbital parameters.
		self.ebparams[eb.PAR_ECOSW]  =  self.planet.ecosw.value  # ecosw
		self.ebparams[eb.PAR_ESINW]  = self.planet.esinw.value  # esinw
		self.ebparams[eb.PAR_P]      = self.planet.period.value  # period
		self.ebparams[eb.PAR_T0]     = self.planet.t0.value + self.planet.dt.value # T0 (epoch of primary eclipse), with an offset of dt applied
		# OTHER NOTES:
		#
		# To do standard transit models (a'la Mandel & Agol),
		# set J=0, q=0, cltt=0, albedo=0.
		# This makes the secondary dark, and disables ellipsoidal and reflection.
		#
		# The strange parameterization of radial velocity is to retain the
		# flexibility to be able to model just light curves, SB1s, or SB2s.
		#
		# For improved precision, it's best to subtract most of the "DC offset"
		# from T0 and the time array (e.g. take off the nominal value of T0 or
		# the midtime of the data array) and add it back on at the end when
		# printing self.ebparams[eb.PAR_T0] and vder[eb.PAR_TSEC].  Likewise the period
		# can cause scaling problems in minimization routines (because it has
		# to be so much more precise than the other parameters), and may need
		# similar treatment.

	def stellar_rv(self, rvc=None, t=None):
		self.set_ebparams()

		# by default, will use the linked RVC, but could use a custom one (e.g. high-resolution for plotting), or just times
		if rvc is None:
			rvc = self.RVC

		if t is None:
			t = rvc.bjd

		# make sure the types are okay for Jonathan's inputs
		typ = np.empty_like(t, dtype=np.uint8)
		typ.fill(eb.OBS_VRAD1)

		rv = self.planet.semiamplitude.value*eb.model(self.ebparams, t, typ) + self.star.gamma.value
		assert(np.isfinite(rv).all())
		return rv

	#@profile
	def planet_model(self, tlc=None, t=None):
		'''Model of the planetary transit.'''
		self.set_ebparams()

		# by default, will use the linked TLC, but could use a custom TLC
		# 	 (e.g. a high-resolution one, for plotting)
		if tlc is None:
			tlc = self.TLC

		# if called with a "t=" keyword set, then will use those custom times
		if t is None:
			t = tlc.bjd

		# make sure the types are okay for Jonathan's inputs
		typ = np.empty_like(t, dtype=np.uint8)
		typ.fill(eb.OBS_MAG)

		# work in relative flux (rather than magnitudes) -- why did I do this?
		return 10**(-0.4*eb.model(self.ebparams, t, typ))

	##@profile
	def instrument_model(self, tlc=None):
		'''Model of the instrument.'''

		# by default, use the real TLC
		if tlc is None:
			tlc = self.TLC

		# use the instrument to spit out a corrective model
		return self.instrument.model(tlc)

	##@profile
	def model(self, tlc=None):
		'''Model including both instrument and planetary transit.'''

		# create the complete model, for either real or fake light curve
		return self.planet_model(tlc=tlc)*self.instrument_model(tlc=tlc)

	@property
	def parameters(self):
		'''Return a list of the parameters that are variable.'''
		try:
			assert(len(self._parameters) == len(self.floating))
			return self._parameters
		except:
			self.defineParameterList()
			return self._parameters

	@parameters.setter
	def parameters(self, **kwargs):
		pass

	def defineParameterList(self):
		'''Set up the parameter list, by pulling the variable parameters out of the subsets.'''

		# define a list containing the keys all the parameters that float
		self.floating = []
		list = []
		for x in (self.planet, self.star, self.instrument):
			d = x.__dict__
			for key in d.keys():
				try:
					if d[key].fixed == False:
						self.floating.append(key)
						list.append(d[key])
				except:
					pass
		self._parameters = np.array(list)

	def	fromArray(self, array):
		'''Use an input array to assign the internal parameter attributes.'''
		count = 0
		for parameter in self.parameters:
			parameter.value = array[count]
			count += 1
		#print count
		#print array
		assert(count > 0)

	def toArray(self):
		'''Define an parameter array, by pulling them out of the internal parameter attributes.'''
		list = []
		parinfolist = []
		for parameter in self.parameters:
			list.append(parameter.value)
			parinfolist.append(parameter.parinfo)
		return list, parinfolist

	def plotPhased(self, smooth=None, **kw):
		'''Plot the light curve model, phased with the planetary period.'''
		t_phased = self.planet.timefrommidtransit(self.smooth_phased_tlc.bjd)
		assert(len(t_phased) == len(self.model(self.smooth_phased_tlc)))

		toplot = self.planet_model(self.smooth_phased_tlc)
		if smooth is not None:
			cadence = np.mean(self.smooth_phased_tlc.bjd[1:] - self.smooth_phased_tlc.bjd[:-1])
			n = np.round(smooth/cadence).astype(np.int)
			kernel = np.ones(n)/n
			toplot = np.convolve(toplot, kernel, 'same')
		else:
			toplot = self.planet_model(self.smooth_phased_tlc)
		plt.plot(t_phased, toplot, **kw)
		'''KLUDGED COMMENTED OUT!'''
		#try:
		#	for phased in [self.line_phased[0], self.line_phased_zoom[0]]:
		#		phased.set_data(t_phased, self.model(self.smooth_phased_tlc))
		#except:
		#	self.line_phased = self.TLC.ax_phased.plot(t_phased,self.model(self.smooth_phased_tlc), **self.kw)
		#	self.line_phased_zoom = self.TLC.ax_phased_zoom.plot(t_phased, self.model(self.smooth_phased_tlc), **self.kw)'''

	def plotUnphased(self):
		'''Plot the light curve model, linear in time.'''
		t_unphased = self.smooth_unphased_tlc.bjd - self.planet.t0.value
		assert(len(t_unphased) == len(self.model(self.smooth_unphased_tlc)))
		try:
			for unphased in [self.line_unphased[0], self.line_unphased_zoom[0]]:
				unphased.set_data(t_unphased, self.model(self.smooth_unphased_tlc))
		except:
			self.line_unphased = self.TLC.ax_unphased.plot(t_unphased, self.model(self.smooth_unphased_tlc), **self.kw)
			self.line_unphased_zoom = self.TLC.ax_unphased_zoom.plot(t_unphased, self.model(self.smooth_unphased_tlc), **self.kw)


	def plotDiagnostics(self):
		'''Plot the light curve model, linear in time.'''
		t_unphased = self.smooth_unphased_tlc.bjd - self.planet.t0.value
		assert(len(t_unphased) == len(self.model(self.smooth_unphased_tlc)))

		#try:
		#	self.line_raw.set_data(t_unphased, self.model(self.smooth_unphased_tlc))
		#	self.line_corrected.set_data(t_unphased, self.planet_model(self.smooth_unphased_tlc))
		#	self.line_residuals.set_data(t_unphased, ppm*np.zeros_like(t_unphased))
		#	self.line_instrument.set_data(t_unphased, ppm*self.instrument_model(self.smooth_unphased_tlc))
		#except:
		# NOT USING?!?
		self.line_raw = self.TLC.ax_raw.plot(t_unphased, self.model(self.smooth_unphased_tlc), **kw)[0]
		self.line_corrected = self.TLC.ax_corrected.plot(t_unphased, self.planet_model(self.smooth_unphased_tlc), **kw)[0]
		self.line_residuals = self.TLC.ax_residuals.plot(t_unphased, ppm*np.zeros_like(t_unphased), **kw)[0]
		self.line_instrument = self.TLC.ax_instrument.plot(t_unphased, ppm*self.instrument_model(self.smooth_unphased_tlc), **kw)[0]

	def plot(self):
		'''Plot the model lines over the existing light curve structures.'''
		self.kw = {'color':self.TLC.colors['lines'], 'linewidth':3, 'alpha':1.0}
		self.plotPhased()
		self.plotUnphased()

		if self.depthassumedforplotting is None:
			self.depthassumedforplotting = self.planet.rp_over_rs.value**2

		# need to work on displaying the parameters...
		try:
			xtext = self.planet.duration/2.0*1.1
			posttransit = self.planet.timefrommidtransit(bjd) > self.planet.duration/2.0
			ytext = np.mean(self.model()[posttransit]) - self.planet.rp_over_rs**2/2.0
			instrument_string = "Instrumental Parameters"
			self.TLC.ax_raw.text(xtext, ytext, instrument_string)
		except:
			pass

	##@profile
	def deviates(self, p, fjac=None, plotting=False):
		'''Return the normalized deviates (an input for mpfit).'''

		# populate the parameter attributes, using the input array
		self.fromArray(p)

		# if necessary, plot the light curve along with this step of the deviates calculation
		status =0
		if plotting:
			self.TLC.LightcurvePlots()

		ok = (self.TLC.bad == 0).nonzero()

		devs = (self.TLC.flux[ok] - self.TM.model()[ok])/self.TLC.uncertainty[ok]

		# add limb darkening priors
		try:
			prioru1 = (self.star.u1.value - self.u1prior_value)/self.u1prior_uncertainty
			prioru2 = (self.star.u2.value - self.u2prior_value)/self.u2prior_uncertainty
			devs = np.append(devs, prioru1)
			devs = np.append(devs, prioru2)
			#print '==============================='
			#print 'u1: ({value} - {center})/{uncertainty}'.format(value = self.star.u1.value, center=self.u1prior_value, uncertainty =self.u1prior_uncertainty)
			#print 'u2: ({value} - {center})/{uncertainty}'.format(value = self.star.u2.value, center=self.u2prior_value, uncertainty =self.u2prior_uncertainty)

		except:
			pass

		# mpfit wants a list with the first element containing a status code
		return [status,devs]

	def applyLDpriors(self):
		self.speak('using atmosphere model as prior on LD coefficients')
		self.u1prior_value = self.star.u1.value + 0.0
		self.u2prior_value = self.star.u2.value + 0.0
		self.u1prior_uncertainty = self.star.u1.uncertainty + 0.0
		self.u2prior_uncertainty = self.star.u2.uncertainty + 0.0

	##@profile
	def lnprob(self, p):
		"""Return the log posterior, calculated from the TM.deviates function (which may have included some conjugate Gaussian priors.)"""



		chisq = np.sum(self.deviates(p)[-1]**2)/2.0
		N = np.sum(self.TLC.bad == 0)

		# sum the deviates into a chisq-like thing
		lnlikelihood = -N * np.log(self.instrument.rescaling.value) - chisq/self.instrument.rescaling.value**2
		if np.isfinite(lnlikelihood) == False:
			lnlikelihood = -1e9

		# initialize an empty constraint, which could freak out if there's something bad about this fit
		constraints = 0.0

		# loop over the parameters


		for parameter in self.parameters:

			# if a parameter is outside its allowed range, then make the constraint very strong!
			inside = (parameter.value < parameter.limits[1]) & (parameter.value > parameter.limits[0])
			try:
				assert(inside)
			except AssertionError:
				constraints -= 1e6

		# return the constrained likelihood
		return lnlikelihood + constraints

	def fastfit(self, **kwargs):
		self.fitter = LM(self, **kwargs)
		self.fitter.fit(**kwargs)

	def slowfit(self, **kwargs):
		self.fitter = MCMC(self, **kwargs)
		self.fitter.fit(**kwargs)

	def __repr__(self):
		return self.TLC.__repr__().replace('TLC', 'TM')
Esempio n. 20
0
def instrument(*args, **kwds):
    'create an instrument that is a container of neutron components'
    from Instrument import Instrument
    return Instrument(*args, **kwds)
Esempio n. 21
0
 def __init__(self, resource):
     Instrument.__init__(self, resource)
     self.inst.timeout = 3000
     self.channels = [1, 2, 3, 4]
Esempio n. 22
0
	def __init__(self, params):
		if 'midi_instr' not in params:
			params["midi_instr"] = randrange(49, 51)
		Instrument.__init__(self, params)
Esempio n. 23
0
 def addInstrument(self, serial, price, spec):
     #print (spec)
     self.inventory.append(Instrument(serial, price, spec))
Esempio n. 24
0
 def __init__(self, resource):
     self.params = []
     self.params.append(arbparams(1))
     self.params.append(arbparams(2))
     Instrument.__init__(self, resource)
Esempio n. 25
0
	def __init__(self, params):
		Instrument.__init__(self, params)
Esempio n. 26
0
 def __init__(self):
     # We have to initialize the instrument first to make sure that the Facet can properly introspect
     # itself.
     Instrument.__init__(self)
     Facet.__init__(self, "Instrument")
     SubstanceInstrumentMixin.__init__(self)
Esempio n. 27
0
 def __init__(self, resource):
     self.vrange = [0.1, 1, 10, 100, 1000]
     self.irange = [0.0001, 0.001, 0.01, 0.1, 1, 3, 10]
     Instrument.__init__(self, resource)
Esempio n. 28
0
class Function_Frame(DMatrix):
    def __init__(self, parameters, path_planner):
        super().__init__()
        self.robots = parameters.robots
        self.tasks = parameters.tasks
        self.path_planner = path_planner
        self.calculating_function_frame()

    def calculating_function_frame(self):
        print("Calculating function frame...")
        self.instrument = Instrument()
        self.instrument.start()

        task_subsets = []
        for i in range(len(self.tasks) + 1):
            task_subsets = task_subsets + [
                Set(list(e)) for e in itertools.combinations(self.tasks, i)
            ]
        task_subsets = Set(task_subsets)

        domain_robots = [e.id for e in self.robots]
        domain_tasks = [set([ee.id for ee in e]) for e in task_subsets]
        self.domain_dict = ["value", "time"]
        self.domain_matrix = [domain_robots, domain_tasks]
        self["value"] = Matrix(
            self.domain_matrix,
            np.zeros((len(domain_robots), len(domain_tasks))))
        self["time"] = Matrix(
            self.domain_matrix,
            np.zeros((len(domain_robots), len(domain_tasks))))

        N = len(task_subsets)
        progress_bar = ProgressBar(N)
        for i_allocation, target_allocation in enumerate(task_subsets):
            progress_bar.progress(i_allocation)
            V_ret, Mu, V, t_eval = self.get_all_function_values(
                target_allocation)
            #save Mu and V ???
            self["value"].matrix[:, i_allocation] = V_ret
            self["time"].matrix[:, i_allocation] = t_eval * np.ones(len(V_ret))
        progress_bar.progress(N, 'Finished!\n')
        calculation_time = self.instrument.stop()
        self.instrument.save_measurement("calculation_time", calculation_time)
        print("Calculation time [s]:")
        print(self.instrument.data)
        print("Finished calculating function frame!\n")

    def get_all_function_values(self, target_allocation):
        targets = []
        for a in target_allocation:
            targets = targets + [a.target]
        goal = self.robots[0].goal
        x_0 = [r.x_0 for r in self.robots]
        instrument = Instrument()
        instrument.start()
        V_ret, Mu, V = self.path_planner.get_solution(targets, goal, x_0)
        t_eval = instrument.stop()
        return V_ret, Mu, V, t_eval

    def get_value(self, r_id, S_r_id):
        return self["value"].get([r_id,
                                  S_r_id]), self["time"].get([r_id, S_r_id])
Esempio n. 29
0
 def __init__(self, resource):  # resource needs to be port (ex: 'COM5')
     Instrument.__init__(self, resource, True)
 def __init__(self, resource, mode = "LAN"):
     Instrument.__init__(self, resource, mode)
Esempio n. 31
0
	def __init__(self, params):
		params["channel"] = 9
		Instrument.__init__(self, params)
Esempio n. 32
0
 def __init__(self, resource):
     self.vrange = [1e-1, 1, 10, 100, 300]
     Instrument.__init__(self, resource)