Example #1
0
    def _onSourceAddEGRETDiffuseSource(self):
        if debug: print ('Source/Add EGRET Diffuse Source')

        # Create a new EGRET diffuse Source.
        name = 'EGRET Diffuse Source %d' % self._getSourceID()

        # Create a power law spectrum for the EGRET diffuse source.
        spectrum = Spectrum(type = 'PowerLaw')

        # Adjust the Prefactor parameter.
        parameter = spectrum.getParameterByName('Prefactor')
        parameter.setValue(11.0)
        parameter.setScale(0.001)
        parameter.setMin(0.001)
        parameter.setMax(1000.0)
        parameter.setFree(True)
        spectrum.setParameterByName('Prefactor', parameter)

        # Adjust the Index parameter.
        parameter = spectrum.getParameterByName('Index')
        parameter.setValue(-2.1)
        parameter.setScale(1.0)
        parameter.setMin(-3.5)
        parameter.setMax(-1.0)
        parameter.setFree(False)
        spectrum.setParameterByName('Index', parameter)

        # Adjust the Scale parameter.
        parameter = spectrum.getParameterByName('Scale')
        parameter.setValue(100.0)
        parameter.setScale(1.0)
        parameter.setMin(50.0)
        parameter.setMax(200.0)
        parameter.setFree(False)
        spectrum.setParameterByName('Scale', parameter)

        # Create a spatial map spatial model.
        spatialModel = SpatialModel(type = 'SpatialMap',
                                    file = ModelEditorApp._EgretDiffuseSourcePath)
        source = Source(name = name, type = 'DiffuseSource',
                        spectrum = spectrum, spatialModel = spatialModel)

        # Assemble the source.
        source = Source(name = name, type = 'DiffuseSource',
                        spectrum = spectrum, spatialModel = spatialModel)

        # Fetch the current SourceLibraryDocument.
        sourceLibraryDocument = self._sourceLibraryDocumentEditor.get()

        # Append the new Source to the list of Sources.
        sourceLibraryDocument.addSource(source)

        # Populate the editor with the changes.
        self._sourceLibraryDocumentEditor.set(sourceLibraryDocument)

        # Select the new source.
        self._sourceLibraryDocumentEditor.selectSource(name)
Example #2
0
class Variable(AbcModel):
    attributeInfos = list(AbcModel.attributeInfos)
    attributeInfos.extend([
        ("source", (Source,Source,Source(),"data")),
        ("formula",(str,STRING,"","formula to compose with other variable data "+\
                                "(ex: 'sin(T)' with 'T' a source name)"+\
                                "It uses numpy expressions")),
        # filter min/max expression
    ])

    def getVariableData(self):
        sourceValues = self.get_source().getSourceData()
        values = self.applyFormula(sourceValues)
        # filters and variable composition could be here ..
        return values

    def applyFormula(self, sourceValues):
        """
        @param sourceValues : np.array
        @param sources : dict
            ex : {'T':<numpyarray>}
        """
        formula = self.get_formula()
        values = sourceValues
        if formula != "":
            container = self.get_container()
            if container is None:
                raise Exception(
                    "variable not registered. Cannot perform formula evaluation"
                )
            sources = self.get_container().getSources()
            values = eval(formula, globals(),
                          {s.get_name(): s.getSourceData()
                           for s in sources})
        return values
Example #3
0
def test_decompile():
	field = Field(Example)

	source = ('[2, 4, 6, 8]', '(0, 1, 1, 0)', '(1, 2)', '(2,)', '[[1, 1], [1, 0]]',
			  'pic_int_zoom_in', 'pic_intp_select_columns', 'pic_nesw_extend', 'pic_vec_recolor_each')

	code = field.compile(Source(source))

	assert code.type == Block.type_no_error

	new_source = field.decompile(code)

	assert field.rex_vector.match(new_source[0].strip())
	assert field.rex_tuple.match(new_source[1].strip())
	assert field.rex_tuple.match(new_source[2].strip())
	assert new_source[3].strip() == '2'
	assert field.rex_picture.match(new_source[4].strip())

	new_source = field.decompile(code, pretty=False)

	assert new_source == source

	new_source = field.decompile(BopForward.bopforward_2pic_recolor_any_rtl)

	assert len(new_source) == 1

	new_source = field.decompile((Block.new_picture(list_of_list=[[4, 0, 4]]), BopForward.bopforward_pic_all_as_pat))

	assert len(new_source) == 2

	with pytest.raises(AttributeError):
		field.decompile((Block.new_picture(list_of_list=[[4, 0, 4]]), 'aa'))
Example #4
0
def test_successful_end_to_end():
	f = Field(Example)

	assert f.from_kind == Question
	assert f.to_kind   == Answer

	assert 'get_question'		 in f.opcode
	assert 'tests_verify_answer' in f.opcode
	assert '2pat_merge_as_pic'	 in f.opcode

	source = Source(('get_question',
					 'pic_all_as_pat',
					 'pat_flip_up_down',
					 'get_question',
					 'pic_all_as_pat',
					 '2pat_merge_as_pic',
					 'tests_verify_answer'))

	code = f.compile(source)

	assert isinstance(code, Code)
	assert len(code.data) == len(source.data)

	ctx = Context('data')
	prb = ctx.get_problem_startswith('496994bd')

	for example in prb:
		ret = f.run(code, example, peek_answer=True)

		assert isinstance(ret, Block)
		assert ret.type == Block.type_integer
		assert isinstance(ret.data, int)

		assert ret.data == 1
Example #5
0
 def add_source(self, sourceParams=None):
     if sourceParams is None:
         sourceParams = {}
     source = Source(**sourceParams)
     self.source_feedback_dict[source.sourceID] =  [[],0.0]
     self.source_action_dict[source.sourceID] = Source.no_agent_action
     self.source_dict[source.sourceID] = source
Example #6
0
def test_MulticoreErrors():
    eval = CodeEval(Example)

    eval.demo_q = [Block.new_picture(list_of_list=[[1, 2, 3]])]
    eval.demo_a = [Block.new_picture(list_of_list=[[4, 0, 4]])]
    eval.question = []

    eval.multicore_clear()

    ret = eval.multicore_run_all(
        Code((Block.new_integer(1), Failing.failing_zero_division,
              Block.new_integer(0), Failing.failing_zero_division)))

    assert ret.type == Block.type_error
    assert ret.data == 'Try/catch caught an exception'

    eval.multicore_clear()

    ret = eval.multicore_run_all(
        eval.compile(Source(('get_question', 'pic_two_col_reverse'))))

    assert ret.type == Block.type_error
    assert ret.data == 'Only two colors expected'

    eval.multicore_clear()

    ret = eval.multicore_run_all(
        eval.compile(
            Source(('get_question', 'pic_fork_on_v_axis_as_pics',
                    'pics_as_2pic'))))

    assert ret.type == Block.type_no_error

    for pl in eval.multicore_state['pic_lists']:
        assert len(pl) == 1

    ret = eval.multicore_run_all(eval.compile(Source(('(2, 4)', ))))

    assert ret.type == Block.type_error
    assert ret.data == 'Code item does not return a picture'

    ret = eval.multicore_run_all(eval.compile(Source(('(2, 4)', ))),
                                 ignore_ret_type=True)

    assert ret.type == Block.type_no_error
Example #7
0
    def _onSourceAddExtragalacticDiffuseSource(self):
        if debug: print 'Source/Add Extragalactic Source'

        # Create a new extragalactic diffuse Source.
        name = 'Extragalactic Diffuse Source %d' % self._getSourceID()

        # Create a power law spectrum for the extragalactic
        # background.
        spectrum = Spectrum(type='PowerLaw')

        # Adjust the Prefactor parameter.
        parameter = spectrum.getParameterByName('Prefactor')
        parameter.setValue(1.6)
        parameter.setScale(1.0e-7)
        parameter.setMin(1.0e-5)
        parameter.setMax(100.0)
        parameter.setFree(True)
        spectrum.setParameterByName('Prefactor', parameter)

        # Adjust the Index parameter.
        parameter = spectrum.getParameterByName('Index')
        parameter.setValue(-2.1)
        parameter.setScale(1.0)
        parameter.setMin(-3.5)
        parameter.setMax(-1.0)
        parameter.setFree(False)
        spectrum.setParameterByName('Index', parameter)

        # Adjust the Scale parameter.
        parameter = spectrum.getParameterByName('Scale')
        parameter.setValue(100.0)
        parameter.setScale(1.0)
        parameter.setMin(50.0)
        parameter.setMax(200.0)
        parameter.setFree(False)
        spectrum.setParameterByName('Scale', parameter)

        # Create a constant value (all-sky) location model.
        spatialModel = SpatialModel(type='ConstantValue')

        # Assemble the source.
        source = Source(name=name,
                        type='DiffuseSource',
                        spectrum=spectrum,
                        spatialModel=spatialModel)

        # Fetch the current SourceLibraryDocument.
        sourceLibraryDocument = self._sourceLibraryDocumentEditor.get()

        # Append the new Source to the list of Sources.
        sourceLibraryDocument.addSource(source)

        # Populate the editor with the changes.
        self._sourceLibraryDocumentEditor.set(sourceLibraryDocument)

        # Select the new source.
        self._sourceLibraryDocumentEditor.selectSource(name)
Example #8
0
def runSimulation(number):
    numOfNodes = number + 1

    nodes = []

    for i in range(numOfNodes):  # initialize nodes
        argv = {}
        argv['ID'] = i
        argv['src'] = i
        argv['des'] = numOfNodes - 1
        n = Source(argv)
        nodes.append(n)

    eventList = []
    #for i in range(numOfNodes-1):
    #	nodes[i].setPacInterval(dataRate)

    for i in range(numOfNodes - 1):
        t = random.randint(20, 150) * 20
        e = initialization(t, i, numOfNodes)
        eventList.append(e)

    min_t = 0

    flag = True
    timer = 20
    data = []
    while True:
        if not eventList:
            break
        elif min_t > fromSecondToSlot(5):  # 6250000  # *4/250000
            break
        else:
            min_index, min_t = min(enumerate(e.time for e in eventList),
                                   key=operator.itemgetter(1))
            newList = action(eventList[min_index], nodes, 'normal')
            eventList.pop(min_index)
            for n in newList:
                eventList.append(n)

        if min_t > fromSecondToSlot(timer):
            # perform the collection
            temp = []
            for i in range(numOfNodes - 1):
                temp.append(nodes[i].getChannelIndicators(450, 160))

            data.append(temp)
            # and set the condition
            timer += 10

    writer = csv.writer(open('data3.csv', 'w'))

    for eachData in data:
        writer.writerow([eachData[0][0], 1.0 - eachData[0][1]])
    return
Example #9
0
def ficheDocumentation(fiche, type_doc, dossier, nom_fichier, graph):
    with open(join(dossier, nom_fichier)) as ref_file:
        content = ref_file.readlines()
        content = [x.strip('\n') for x in content]
        for line in content:
            if (type_doc == "references"):
                ref_id, _, ref_leg = line.partition('@')
                if ref_id in fiche.get_references():
                    reference_trouvee = Source('Reference', ref_leg)
                    reference_trouvee.create_source(graph)
                    fiche.create_doc(graph, reference_trouvee, '')
            elif (type_doc == "images"):
                infos = line.split('@')
                fiche_id = infos[0]
                filename = infos[1]
                legende = infos[2]
                if fiche_id == fiche.get_tmp_id():
                    reference_trouvee = Source('Image', legende, filename)
                    reference_trouvee.create_source(graph)
                    fiche.create_doc(graph, reference_trouvee, '')
Example #10
0
    def on_new_pa_source(self, index, struct, props):
        if not self.pa_sources.has_key(index):
            self.__print("new source:", index, struct.name)
            # create new
            self.pa_sources[index] = Source(index, struct, props)
        else:
            self.__print("changed source:", index, struct.name)
            # update old
            self.pa_sources[index].update(struct, props)

        self.update()
Example #11
0
 def setFeeds(self, feedNames ):
     from Source import Source
     sources = self.pxManager.getRxNames()
     for name in feedNames :
         if not name in sources : continue
         instant = Source(name, self.logger, False)
         if instant.type == 'am' or instant.type == 'amqp' or instant.type == 'wmo' :
            self.logger.warning("Feed (source %s) will be ignored  (type %s)" % (name, instant.type) )
            continue
         self.feedNames.append(name)
         self.feeds[name] = instant
     self.logger.info("Ingestor (source %s) can link files to receiver: %s" % (self.source.name, self.feedNames))
Example #12
0
def assert_error(source_tuple, error_msg):
    field = Field(Example)

    code = field.compile(Source(source_tuple))

    assert isinstance(code, Code)

    ret = field.run(code)

    assert isinstance(ret, Block)
    assert ret.type == Block.type_error
    assert ret.data == error_msg
Example #13
0
 def setClients(self):
     """"
     Set a dictionnary of Clients. Main usage will be to access value of 
     configuration options (mainly masks) of the Client objects.
     """
     from Source import Source
     from Sourlient import Sourlient
     for name in self.clientNames:
         self.clients[name] = Client(name, self.logger)
     for name in self.filterNames:
         self.clients[name] = Source(name, self.logger, False, True)
     for name in self.sourlientNames:
         self.clients[name] = Sourlient(name, self.logger, False)
Example #14
0
    def __init__(self, p=0.75, p1=0.8, p2=0.5, iteration_count=100000):
        self.current_tick = 0
        self.handled_tasks = []
        self.states = []
        self.iteration_count = iteration_count
        self.busy_count = 0

        self.source = Source(p, LemerGenerator(209715120, 3, 7))
        self.queue = TaskQueue(2)
        self.handlers = [
            Handler(p1, LemerGenerator(209715120, 3, 7)),
            Handler(p2, LemerGenerator(209715120, 3, 7))
        ]
Example #15
0
	def load(self, file_name, abstract_relation):
		"""
		This loads and compiles a collection of code snippets from a text file.

		The snippets are appended to the content already in the CodeBase. Names cannot
		match any of the names already in the CodeBase.

		It requires a Relation Class for a language definition for compiling.
		"""
		field = Field(abstract_relation)

		with open(file_name, 'r') as f:
			txt = f.read().splitlines()

		if not txt[0].startswith('.bopDB'):
			raise ValueError

		name = None
		for line in txt[3:]:
			if name is None:
				if line == '.eof.':
					return

				name   = line
				source = None
				sample = None
			elif line.startswith('-'):
				source_tuple = ()
			elif line == '':
				if source is None:
					source = Source(source_tuple)
					code   = field.compile(source)
					if code.type == Block.type_error:
						raise ValueError
				else:
					self.add(code, source, name, sample)
					name = None
			else:
				if source is None:
					source_tuple = source_tuple + (line,)
				else:
					try:
						pic = eval(line)
					except Exception:
						raise ValueError

					sample = Block.new_picture(list_of_list=pic)

		raise ValueError
Example #16
0
    def _onSourceAddGALPROPDiffuseSource(self):
        if debug: print 'Source/Add GALPROP Diffuse Source'

        # Create a new GALPROP diffuse Source.
        name = 'GALPROP Diffuse Source %d' % self._getSourceID()

        # Create a constant value spectrum for the GALPROP source.
        spectrum = Spectrum(type='ConstantValue')

        # Adjust the Value parameter.
        parameter = spectrum.getParameterByName('Value')
        parameter.setValue(1.0)
        parameter.setScale(1.0)
        parameter.setMin(0.0)
        parameter.setMax(10.0)
        parameter.setFree(True)
        spectrum.setParameterByName('Value', parameter)

        # Create a map cube spatial model.
        spatialModel = SpatialModel(
            type='MapCubeFunction',
            file=ModelEditorApp._GalpropDiffuseSourcePath)

        # Adjust the Normalization parameter.
        parameter = spatialModel.getParameterByName('Normalization')
        parameter.setValue(1.0)
        parameter.setScale(1.0)
        parameter.setMin(0.001)
        parameter.setMax(1000.0)
        parameter.setFree(False)
        spatialModel.setParameterByName('Normalization', parameter)

        # Assemble the source.
        source = Source(name=name,
                        type='DiffuseSource',
                        spectrum=spectrum,
                        spatialModel=spatialModel)

        # Fetch the current SourceLibraryDocument.
        sourceLibraryDocument = self._sourceLibraryDocumentEditor.get()

        # Append the new Source to the list of Sources.
        sourceLibraryDocument.addSource(source)

        # Populate the editor with the changes.
        self._sourceLibraryDocumentEditor.set(sourceLibraryDocument)

        # Select the new source.
        self._sourceLibraryDocumentEditor.selectSource(name)
Example #17
0
    def _onSourceAddDiffuseSource(self):
        if debug: print 'Source/Add Diffuse Source'

        # Create a new diffuse Source.
        name = 'Diffuse Source %d' % self._getSourceID()
        source = Source(name=name, type='DiffuseSource')

        # Fetch the current SourceLibraryDocument.
        sourceLibraryDocument = self._sourceLibraryDocumentEditor.get()

        # Append the new Source to the list of Sources.
        sourceLibraryDocument.addSource(source)

        # Populate the editor with the changes.
        self._sourceLibraryDocumentEditor.set(sourceLibraryDocument)
Example #18
0
    def retrieveSource(self, sourceNum, probeInfo):
        """

        """
        sourceNum -= 1

        try:
            name = str(sourceNum + 1)
            locationName = probeInfo['probeInfo'][0][0]['probes']['labels_s'][
                0][0][0][sourceNum][0]
            xCoord = probeInfo['probeInfo'][0][0]['probes']['coords_s3'][0][0][
                sourceNum][0]
            yCoord = probeInfo['probeInfo'][0][0]['probes']['coords_s3'][0][0][
                sourceNum][1]
            zCoord = probeInfo['probeInfo'][0][0]['probes']['coords_s3'][0][0][
                sourceNum][2]
            self.source = Source(xCoord, yCoord, zCoord, name, locationName)
        except KeyError:
            print("Source parsing failed")
Example #19
0
def assert_equal(source_tuple, add_compare=True, val=1):
    field = Field(Example)

    code = field.compile(Source(source_tuple))

    assert isinstance(code, Code)

    example = None
    if add_compare:
        code = Code(code.data + (BopBack.bopback_tests_verify_answer, ))

        answer = code.data[0]

        example = Example([4, 0, 4], answer.data.tolist(), False)

    ret = field.run(code, example)

    assert isinstance(ret, Block)
    assert ret.type == Block.type_integer
    assert isinstance(ret.data, int)

    assert ret.data == val
Example #20
0
    def __init__(self):
        self.generador = Source(1)
        self.cuaMainGate = 0
        self.cuaParking = 0
        for i in range(0, 2):
            #print("inicializacion de los maingates" + str(i))
            self.MainGate[i] = MainGate(i)
        for i in range(0, 2):
            self.Parking[i] = PosicioParking(i)
        for i in range(0, 2):
            self.Estibadors[i] = Estibador(i)

        self.esdevenimentsPendents = []
        self.esdevenimentsProcessats = []
        self.cuaParkingMaingates = []
        self.cuaEstibadorsParking = []
        self.CEPCamions = []
        self.CPMCamions = []
        self.CMCamions = []

        self.currentTime = 0

        self.inicialitzarLlistaEsdeveniments()