index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
74,914
AvinashKalivarapu/SentimentAnalysisOfTwitter
refs/heads/master
/processTweets_p1.py
import re from DictionaryBuilder import * #Creating Dictionaries ed=getEmoticonDictionary() ad=getAcronymDictionary() swd=getStopwordDictionary() specialChar='1234567890#@%^&()_=`{}:"|[]\;\',./\n\t\r ' """ eg greaaaaaaaaaaaaat->greaaat param: tweet - list of words in tweet return: list of words and count of words which has repitetion""" def replaceRepetition(tweet): for i in range(len(tweet)): x=list(tweet[i]) if len(x)>3: flag=0 for j in range(3,len(x)): if(x[j-3]==x[j-2]==x[j-1]==x[j]): x[j-3]='' if flag==0: flag=1 tweet[i]=''.join(x).strip(specialChar) return tweet """remove the non-english or better non-ascii characters param: list of words in tweets return: tweet with English words only and the count of words removed.""" def removeNonEnglishWords(tweet): newTweet=[] for i in range(len(tweet)): if tweet[i]!='': chk=re.match(r'([a-zA-z0-9 \+\?\.\*\^\$\(\)\[\]\{\}\|\\/:;\'\"><,.#@!~`%&-_=])+$',tweet[i]) if chk: newTweet.append(tweet[i]) return newTweet """Removes the stopwords. param: list of words in tweet,a Dictonary of stopword. return: modified list words """ def removeStopWords(stopWordsDict,tweet): newTweet=[] for i in range(len(tweet)): if tweet[i].strip(specialChar) not in stopWordsDict: newTweet.append(tweet[i]) return newTweet """ replaces the emoticons present in tweet with its polarity param : emoticons dictioary emoticons as key polarity as value return: list which contains words in tweet and return list of words in tweet after replacement""" def replaceEmoticons(emoticonsDict,tweet): for i in range(len(tweet)): if tweet[i] in emoticonsDict: tweet[i]=emoticonsDict[tweet[i]] return tweet """expand the Acronym in tweet param: acronym dictionary ,acronym as key and abbreviation as value,list of words in tweet. return: list of words in tweet after expansion and their count""" def expandAcronym(acronymDict,tweet): newTweet=[] for i in range(len(tweet)): word=tweet[i].strip(specialChar) if word: if word in acronymDict: newTweet+=acronymDict[word].split(" ") else: newTweet+=[tweet[i]] return newTweet """param: list of words in tweet return: list of words in tweet after expanding" eg isn't -> is not """ def expandNegation(tweet): newTweet=[] for i in range(len(tweet)): word=tweet[i].strip(specialChar) if(word[-3:]=="n't"): if word[-5:]=="can't" : newTweet.append('can') else: newTweet.append(word[:-3]) newTweet.append('not') else: newTweet.append(tweet[i]) return newTweet """param: a list which contains words in tweet. return: list of words in tweet after replacement ("not","n't","no","~") eg. not -> negation isn't -> negation """ def replaceNegation(tweet): for i in range(len(tweet)): word=tweet[i].lower().strip(specialChar) if(word=="no" or word=="not" or word.count("n't")>0): tweet[i]='negation' return tweet """ replace url with IURLI """ def replaceURL(tweet): tweet=re.sub('((www\.[^\s]+)|(https?://[^\s]+))','IURLI',tweet) return tweet """ eg: replace @sunil with IATUSERI """ def replaceTarget(tweet): tweet=re.sub('@[^\s]+','IATUSERI',tweet) return tweet """ param: tweet as a string return: list of words in tweet after removing numbers """ def removeNumbers(tweet): tweet=re.sub('^[0-9]+', '', tweet) return tweet """param: string tweet return: list of words in tweet after replacement eg : #*** - > *** """ def replaceHashtag(tweet): tweet=re.sub(r'#([^\s]+)', r'\1', tweet) return tweet def mergeSpace(tweet): return re.sub('[\s]+', ' ', tweet) """ Intial preprocessing param: tweet string return: preprocessed tweet """ def processTweet(tweet,ed,ad,swd): tweet=tweet.lower() tweet = replaceURL(tweet) tweet = replaceTarget(tweet) tweet = replaceHashtag(tweet) #print "After url hashtag target",tweet tweet = mergeSpace(tweet) tweet = tweet.strip('\'"') tweet=tweet.strip(' ') tweet=tweet.split(" ") tweet=removeNonEnglishWords(tweet) #print "Non English",tweet tweet=replaceRepetition(tweet) #print "Repetition",tweet tweet=replaceEmoticons(ed,tweet) #print "Emoticons",tweet tweet=expandAcronym(ad,tweet) #print "Acronym",tweet tweet=expandNegation(tweet) tweet=replaceNegation(tweet) #print "Negation",tweet tweet=removeStopWords(swd,tweet) #print "Stop Words",tweet return tweet
{"/preprocess_p1.py": ["/processTweets_p1.py", "/DictionaryBuilder.py"], "/processTweets.py": ["/DictionaryBuilder.py"], "/preprocess.py": ["/processTweets.py", "/DictionaryBuilder.py"], "/processTweets_p1.py": ["/DictionaryBuilder.py"]}
74,915
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/setup.py
#!/usr/bin/env python from setuptools import setup setup(name='fpgaedu', version='0.1', author='Matthijs Bos', packages=['fpgaedu'], install_requires=['myhdl', 'pytest-runner'], test_suite='pytest-runner', tests_require=['pytest', 'pytest-xdist'] )
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,916
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/generatevhdl.py
import os from myhdl import toVHDL, toVerilog, Signal, ResetSignal, intbv from fpgaedu import ControllerSpec from fpgaedu.hdl import (BaudGen, UartRx, UartTx, BaudGenRxLookup, Rom, Fifo, Controller) from fpgaedu.hdl import nexys4 from fpgaedu.hdl.testexperiment._experiment_setup import ExperimentSetup # Instance constants _CLK_FREQ = 100000000 _UART_BAUDRATE = 9600 _UART_RX_DIV = 16 _UART_DATA_BITS = 8 _UART_STOP_BITS = 1 _WIDTH_DATA = 8 _WIDTH_ADDR = 32 _SPEC = ControllerSpec(_WIDTH_ADDR, _WIDTH_DATA) _EXP_RESET_ACTIVE = True _WIDTH_COUNT = 8 # toVHDL() constants _STD_LOGIC_PORTS = True _OUTPUT_DIRECTORY = './vhdl/' # Signals _CLK = Signal(False) _RESET = ResetSignal(True, active=False, async=False) _ENABLE = Signal(False) _COUNT = Signal(intbv()[_WIDTH_COUNT:0]) _UART_RX = Signal(False) _UART_RX_TICK = Signal(False) _UART_RX_DATA = Signal(intbv(0)[_UART_DATA_BITS:0]) _UART_RX_FINISH = Signal(False) _UART_RX_BUSY = Signal(False) _UART_RX_BAUD_TICK = Signal(False) _UART_TX = Signal(False) _UART_TX_TICK = Signal(False) _UART_TX_DATA = Signal(intbv(0)[_UART_DATA_BITS:0]) _UART_TX_START = Signal(False) _UART_TX_BUSY = Signal(False) _UART_TX_BAUD_TICK = Signal(False) _FIFO_DIN = Signal(intbv(0)[32:0]) _FIFO_DOUT = Signal(intbv(0)[32:0]) _FIFO_ENQUEUE = Signal(False) _FIFO_DEQUEUE = Signal(False) _FIFO_EMPTY = Signal(False) _FIFO_FULL = Signal(False) _TX_FIFO_DIN = Signal(intbv(0)[_SPEC.width_message:0]) _TX_FIFO_DOUT = Signal(intbv(0)[_SPEC.width_message:0]) _TX_FIFO_ENQUEUE = Signal(False) _TX_FIFO_DEQUEUE = Signal(False) _TX_FIFO_EMPTY = Signal(False) _TX_FIFO_FULL = Signal(False) _RX_FIFO_DIN = Signal(intbv(0)[_SPEC.width_message:0]) _RX_FIFO_DOUT = Signal(intbv(0)[_SPEC.width_message:0]) _RX_FIFO_ENQUEUE = Signal(False) _RX_FIFO_DEQUEUE = Signal(False) _RX_FIFO_EMPTY = Signal(False) _RX_FIFO_FULL = Signal(False) _EXP_ADDR = Signal(intbv(0)[_SPEC.width_addr:0]) _EXP_DIN = Signal(intbv(0)[_SPEC.width_data:0]) _EXP_DOUT = Signal(intbv(0)[_SPEC.width_data:0]) _EXP_WEN = Signal(False) _EXP_RESET = Signal(False) _EXP_CLK = Signal(False) _EXP_CLK_EN = Signal(False) def _create_output_directory(): if not os.path.exists(_OUTPUT_DIRECTORY): os.makedirs(_OUTPUT_DIRECTORY) def _set_tovhdl_defaults(name, directory=_OUTPUT_DIRECTORY): toVHDL.std_logic_ports = True toVHDL.name = name toVHDL.directory = directory toVHDL.use_clauses = \ ''' Library UNISIM; use UNISIM.vcomponents.all; use work.pck_myhdl_090.all; ''' toVerilog.name = name toVerilog.directory = directory def _generate_baudgen_rx_lookup(): _set_tovhdl_defaults('baudgen_rx_lookup') toVHDL(BaudGenRxLookup, _RX_LOOKUP_DOUT, _RX_LOOKUP_ADDR) def _generate_uart_rx(): _set_tovhdl_defaults('uart_rx') toVHDL(UartRx, _CLK, _RESET, _UART_RX, _UART_RX_DATA, _UART_RX_FINISH, _UART_RX_BUSY, _UART_RX_BAUD_TICK, data_bits=_UART_DATA_BITS, stop_bits=_UART_STOP_BITS, rx_div=_UART_RX_DIV) def _generate_uart_tx(): _set_tovhdl_defaults('uart_tx') toVHDL(UartTx, clk=_CLK, reset=_RESET, tx=_UART_TX, tx_data=_UART_TX_DATA, tx_start=_UART_TX_START, tx_busy=_UART_TX_BUSY, baud_tick=_UART_TX_BAUD_TICK, data_bits=_UART_DATA_BITS, stop_bits=_UART_STOP_BITS) def _generate_baudgen(): _set_tovhdl_defaults('baudgen') toVHDL(BaudGen, _CLK, _RESET, _UART_RX_TICK, _UART_TX_TICK, clk_freq=_CLK_FREQ, baudrate=_UART_BAUDRATE, rx_div=_UART_RX_DIV) def _generate_fifo(): _set_tovhdl_defaults('fifo') toVHDL(Fifo, _CLK, _RESET, _FIFO_DIN, _FIFO_ENQUEUE, _FIFO_DOUT, _FIFO_DEQUEUE, _FIFO_EMPTY, _FIFO_FULL) def _generate_controller(): _set_tovhdl_defaults('controller') toVHDL(Controller, spec=_SPEC, clk=_CLK, reset=_RESET, rx_fifo_data_read=_RX_FIFO_DOUT, rx_fifo_dequeue=_RX_FIFO_DEQUEUE, rx_fifo_empty=_RX_FIFO_EMPTY, tx_fifo_data_write=_TX_FIFO_DIN, tx_fifo_enqueue=_TX_FIFO_ENQUEUE, tx_fifo_full=_TX_FIFO_FULL, exp_addr=_EXP_ADDR, exp_data_write=_EXP_DIN, exp_data_read=_EXP_DOUT, exp_wen=_EXP_WEN, exp_reset=_EXP_RESET, exp_clk_en=_EXP_CLK_EN, exp_reset_active=_EXP_RESET_ACTIVE) def _generate_nexys4_clock_enable_buffer(): _set_tovhdl_defaults('nexys4bufgce') toVHDL(nexys4.ClockEnableBuffer, clk_in=_CLK, clk_out=_EXP_CLK, clk_en=_EXP_CLK_EN) def _generate_nexys4_board_component(): _set_tovhdl_defaults('nexys4boardcomponent') toVHDL(nexys4.BoardComponent, spec=_SPEC, clk=_CLK, reset=_RESET, rx=_UART_RX, tx=_UART_TX, exp_addr=_EXP_ADDR, exp_data_write=_EXP_DIN, exp_data_read=_EXP_DOUT, exp_wen=_EXP_WEN, exp_reset=_EXP_RESET, exp_clk=_EXP_CLK, exp_reset_active=_EXP_RESET_ACTIVE, baudrate=_UART_BAUDRATE) def _generate_nexys4_test_setup(): _set_tovhdl_defaults('nexys4testsetup') toVHDL(nexys4.TestSetup, _SPEC, _CLK, _RESET, _UART_RX, _UART_TX) #toVerilog(nexys4.TestSetup, _SPEC, _CLK, _RESET, _UART_RX, _UART_TX) def _generate_counter(): _set_tovhdl_defaults('counter') toVHDL(ExperimentSetup, _CLK, _RESET, _ENABLE, _COUNT, _WIDTH_COUNT) if __name__ == '__main__': _create_output_directory() #_generate_rom() #_generate_baudgen_rx_lookup() #_generate_controller() #_generate_uart_rx() #_generate_uart_tx() #_generate_baudgen() #_generate_fifo() #_generate_nexys4_clock_enable_buffer() _generate_nexys4_board_component() _generate_nexys4_test_setup() _generate_counter()
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,917
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_test_experiment.py
from myhdl import always_comb def TestExperiment(clk, reset, addr, din, dout, wen): ''' input signals: clk reset addr din wen output signals: dout ''' @always_comb def logic(): dout.next = (addr +1)% (256) clk.read = True reset.read = True din.read = True wen.read = True return logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,918
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_controller_control.py
from myhdl import (Signal, ResetSignal, intbv, always, instance, Simulation, StopSimulation, delay) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl._controller_control import ControllerControl class ControllerControlTestCase(TestCase): WIDTH_ADDR = 32 WIDTH_DATA = 8 EXP_RESET_ACTIVE = False def setUp(self): self.spec = ControllerSpec(self.WIDTH_ADDR, self.WIDTH_DATA) # input signals self.opcode_cmd = Signal(intbv(0)[self.spec.width_opcode:0]) self.rx_ready = Signal(False) self.tx_ready = Signal(False) self.cycle_autonomous = Signal(False) self.reset = ResetSignal(True, active=False, async=False) # output signals self.rx_next = Signal(False) self.opcode_res = Signal(intbv(0)[self.spec.width_message:0]) self.nop = Signal(False) self.exp_wen = Signal(False) self.exp_reset = ResetSignal(True, active=self.EXP_RESET_ACTIVE, async=False) self.cycle_start = Signal(False) self.cycle_pause = Signal(False) self.cycle_step = Signal(False) self.control = ControllerControl(spec=self.spec, reset=self.reset, opcode_cmd=self.opcode_cmd, opcode_res=self.opcode_res, rx_ready=self.rx_ready, rx_next=self.rx_next, tx_ready=self.tx_ready, nop=self.nop, exp_wen=self.exp_wen, exp_reset=self.exp_reset, cycle_autonomous=self.cycle_autonomous, cycle_start=self.cycle_start, cycle_pause=self.cycle_pause, cycle_step=self.cycle_step, exp_reset_active=self.EXP_RESET_ACTIVE) def simulate(self, test_logic, duration=None): sim = Simulation(self.control, test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_exp_wen(self): @instance def test(): self.opcode_cmd.next = self.spec.opcode_cmd_read self.rx_ready.next = False self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.exp_wen) self.opcode_cmd.next = self.spec.opcode_cmd_write yield delay(10) self.assertFalse(self.exp_wen) self.rx_ready.next = True self.tx_ready.next = False yield delay(10) self.assertFalse(self.exp_wen) self.rx_ready.next = False self.tx_ready.next = True yield delay(10) self.assertFalse(self.exp_wen) self.rx_ready.next = True self.tx_ready.next = True yield delay(10) self.assertTrue(self.exp_wen) self.cycle_autonomous.next = True yield delay(10) self.assertFalse(self.exp_wen) self.stop_simulation() self.simulate(test) def test_exp_reset(self): @instance def test(): yield delay(10) self.opcode_cmd.next = self.spec.opcode_cmd_reset self.rx_ready.next = False self.tx_ready.next = False yield delay(10) self.assertEquals(self.exp_reset, not self.EXP_RESET_ACTIVE) self.opcode_cmd.next = self.spec.opcode_cmd_reset self.rx_ready.next = True self.tx_ready.next = False yield delay(10) self.assertEquals(self.exp_reset, not self.EXP_RESET_ACTIVE) self.opcode_cmd.next = self.spec.opcode_cmd_reset self.rx_ready.next = False self.tx_ready.next = True yield delay(10) self.assertEquals(self.exp_reset, not self.EXP_RESET_ACTIVE) self.opcode_cmd.next = self.spec.opcode_cmd_reset self.rx_ready.next = True self.tx_ready.next = True yield delay(10) self.assertEquals(self.exp_reset, self.EXP_RESET_ACTIVE) # assert that the exp_reset signal is activated when the controller # reset signal is activated self.reset.next = self.reset.active yield delay(10) self.assertEquals(self.exp_reset, self.EXP_RESET_ACTIVE) self.stop_simulation() self.simulate(test) def test_nop_dequeue(self): @instance def test(): self.rx_ready.next = False self.tx_ready.next = False yield delay(10) self.assertTrue(self.nop) self.assertFalse(self.rx_next) self.rx_ready.next = True self.tx_ready.next = True yield delay(10) self.assertFalse(self.nop) self.assertTrue(self.rx_next) self.rx_ready.next = True self.tx_ready.next = False yield delay(10) self.assertTrue(self.nop) self.assertFalse(self.rx_next) self.rx_ready.next = True self.tx_ready.next = True yield delay(10) self.assertFalse(self.nop) self.assertTrue(self.rx_next) self.rx_ready.next = False self.tx_ready.next = True yield delay(10) self.assertTrue(self.nop) self.assertFalse(self.rx_next) self.stop_simulation() self.simulate(test) def test_opcode_res(self): @instance def test(): self.rx_ready.next = True self.tx_ready.next = True self.cycle_autonomous.next = False def test_opcode(cmd, res_expected): self.opcode_cmd.next = cmd yield delay(10) self.assertEquals(self.opcode_res, res_expected) yield test_opcode(self.spec.opcode_cmd_read, self.spec.opcode_res_read_success) yield test_opcode(self.spec.opcode_cmd_write, self.spec.opcode_res_write_success) yield test_opcode(self.spec.opcode_cmd_reset, self.spec.opcode_res_reset_success) yield test_opcode(self.spec.opcode_cmd_step, self.spec.opcode_res_step_success) yield test_opcode(self.spec.opcode_cmd_start, self.spec.opcode_res_start_success) yield test_opcode(self.spec.opcode_cmd_pause, self.spec.opcode_res_pause_error_mode) yield test_opcode(self.spec.opcode_cmd_status, self.spec.opcode_res_status) self.cycle_autonomous.next = True yield delay(10) yield test_opcode(self.spec.opcode_cmd_read, self.spec.opcode_res_read_error_mode) yield test_opcode(self.spec.opcode_cmd_write, self.spec.opcode_res_write_error_mode) yield test_opcode(self.spec.opcode_cmd_reset, self.spec.opcode_res_reset_success) yield test_opcode(self.spec.opcode_cmd_step, self.spec.opcode_res_step_error_mode) yield test_opcode(self.spec.opcode_cmd_start, self.spec.opcode_res_start_error_mode) yield test_opcode(self.spec.opcode_cmd_pause, self.spec.opcode_res_pause_success) yield test_opcode(self.spec.opcode_cmd_status, self.spec.opcode_res_status) self.stop_simulation() self.simulate(test) def test_cycle_start(self): @instance def test(): yield delay(10) # rx empty, tx full, no start self.opcode_cmd.next = self.spec.opcode_cmd_start self.rx_ready.next = False self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_start) # tx full, no start self.opcode_cmd.next = self.spec.opcode_cmd_start self.rx_ready.next = True self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_start) # rx empty, no start self.opcode_cmd.next = self.spec.opcode_cmd_start self.rx_ready.next = False self.tx_ready.next = True self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_start) # should signal start now self.opcode_cmd.next = self.spec.opcode_cmd_start self.rx_ready.next = True self.tx_ready.next = True self.cycle_autonomous.next = False yield delay(10) self.assertTrue(self.cycle_start) # cycle controller in autonomous mode, should no longer signal # start self.cycle_autonomous.next = True yield delay(10) self.assertFalse(self.cycle_start) self.reset.next = self.reset.active yield delay(10) self.assertFalse(self.cycle_start) self.stop_simulation() self.simulate(test) def test_cycle_pause(self): @instance def test(): yield delay(10) # rx empty, tx full, no pause self.opcode_cmd.next = self.spec.opcode_cmd_pause self.rx_ready.next = False self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_pause) # rx empty, no pause self.opcode_cmd.next = self.spec.opcode_cmd_pause self.rx_ready.next = False self.tx_ready.next = True self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_pause) # tx full, no pause self.opcode_cmd.next = self.spec.opcode_cmd_pause self.rx_ready.next = True self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_pause) # cycle controller not in autonomous mode, no pause self.opcode_cmd.next = self.spec.opcode_cmd_pause self.rx_ready.next = True self.tx_ready.next = True self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_pause) # cycle controller in autonomous mode, pause signal self.opcode_cmd.next = self.spec.opcode_cmd_pause self.rx_ready.next = True self.tx_ready.next = True self.cycle_autonomous.next = True yield delay(10) self.assertTrue(self.cycle_pause) # cycle controller switches to manual mode, no longer a pause # signal emitted self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_pause) self.stop_simulation() self.simulate(test) def test_cycle_step(self): @instance def test(): yield delay(10) # rx empty, tx full, no step self.opcode_cmd.next = self.spec.opcode_cmd_step self.rx_ready.next = False self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_step) # tx full, no step self.opcode_cmd.next = self.spec.opcode_cmd_step self.rx_ready.next = True self.tx_ready.next = False self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_step) # rx empty, no step self.opcode_cmd.next = self.spec.opcode_cmd_step self.rx_ready.next = False self.tx_ready.next = True self.cycle_autonomous.next = False yield delay(10) self.assertFalse(self.cycle_step) # in autonomous mode, no step self.opcode_cmd.next = self.spec.opcode_cmd_step self.rx_ready.next = True self.tx_ready.next = True self.cycle_autonomous.next = True yield delay(10) self.assertFalse(self.cycle_step) # not in autonomous mode, no step self.opcode_cmd.next = self.spec.opcode_cmd_step self.rx_ready.next = True self.tx_ready.next = True self.cycle_autonomous.next = False yield delay(10) self.assertTrue(self.cycle_step) self.stop_simulation() self.simulate(test)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,919
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_ram.py
from myhdl import Signal, intbv, always, always_comb def Ram(clk, dout, din, addr, wen, data_width=8, depth=128): """ Ram model http://docs.myhdl.org/en/stable/manual/conversion_examples.html#ram-inference """ mem = [Signal(intbv(0)[data_width:]) for i in range(depth)] @always(clk.posedge) def write(): if we: mem[addr].next = din @always_comb def read(): dout.next = mem[addr] return write, read
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,920
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_clockgen.py
from myhdl import delay, always def ClockGen(clk, half_period): interval = delay(half_period) @always(interval) def logic(): clk.next = not clk return logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,921
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/shell.py
#!/usr/bin/env python3 import struct import cmd, sys import serial from serial.tools.list_ports import comports from fpgaedu import ControllerSpec import argparse #BAUDRATE = 115200 BAUDRATE = 9600 class FpgaEduArgumentError(Exception): pass class FpgaEduArgumentParser(argparse.ArgumentParser): def error(self, message=None): self.print_usage() raise FpgaEduArgumentError() class FpgaEduShell(cmd.Cmd): intro = 'Welcome to the fpgaedu shell' prompty = '(fpgaedu)' connection = None spec = ControllerSpec(1,8) def do_list_ports(self, arg): ports = comports() if len(ports) <= 0: print ('no com ports found on system') for port in ports: print(port.name) def postloop(self): self.do_disconnect() def do_connect(self, arg): try: self.connection = serial.Serial(arg, baudrate=BAUDRATE) print('Started connection') except serial.SerialException: try: self.connection = serial.Serial('/dev/'+arg, baudrate=BAUDRATE) except serial.SerialException: print('Unable to open the specified port') def do_disconnect(self, arg): if self.connection is serial.Serial: self.connection.close() del self.connection def do_read(self, arg): readparser = FpgaEduArgumentParser() readparser.add_argument('addr', type=int) try: n = readparser.parse_args(arg.split()) except FpgaEduArgumentError as err: return self.write_addr_type_cmd(self.spec.opcode_cmd_read, n.addr, 0) self.read_res() def do_write(self, arg): writeparser = FpgaEduArgumentParser() writeparser.add_argument('addr', type=int) writeparser.add_argument('data', type=int) try: n = writeparser.parse_args(arg.split()) except FpgaEduArgumentError as err: return self.write_addr_type_cmd(self.spec.opcode_cmd_write, n.addr, n.data) self.read_res() pass def do_reset(self, arg): self.write_value_type_cmd(self.spec.opcode_cmd_reset, 0) self.read_res() def do_step(self, arg): self.write_value_type_cmd(self.spec.opcode_cmd_step, 0) self.read_res() def do_start(self, arg): self.write_value_type_cmd(self.spec.opcode_cmd_start, 0) self.read_res() def do_pause(self, arg): self.write_value_type_cmd(self.spec.opcode_cmd_pause, 0) self.read_res() def do_status(self, arg): self.write_value_type_cmd(self.spec.opcode_cmd_status, 0) self.read_res() def write_addr_type_cmd(self, opcode, addr, data): cmd = struct.pack('>BBIBB', self.spec.chr_start, opcode, addr, data, self.spec.chr_stop) print('sending address-type command') print(repr(cmd)) self.connection.write(cmd) def write_value_type_cmd(self, opcode, value): cmd = struct.pack('>BBIBB', self.spec.chr_start, opcode, 0, value, self.spec.chr_stop) print('sending value-type command') print(repr(cmd)) self.connection.write(cmd) def read_res(self): message = [None for i in range(6)] if self.connection: self.connection.timeout = 0.1 esc = False message = bytes(0) #read start byte while True: res = self.connection.read(1) if not esc and res == bytes([self.spec.chr_start]): break if not esc and res == bytes([self.spec.chr_esc]): esc = True else: esc = False #read message bytes while True: res = self.connection.read(1) if not esc and res == bytes([self.spec.chr_start]): message = bytes(0) elif not esc and res == bytes([self.spec.chr_stop]): break else: message += res if not esc and res == bytes([self.spec.chr_esc]): esc = True else: esc = False print(repr(message)) opcode = int.from_bytes(message[0:1], byteorder='big') addr = int.from_bytes(message[1:5], byteorder='big') data = int.from_bytes(message[5:6], byteorder='big') value = int.from_bytes(message[1:6], byteorder='big') if opcode == self.spec.opcode_res_read_success: print('read success: addr=%s, data=%s' % (addr, data)) elif opcode == self.spec.opcode_res_read_error_mode: print('read error: controller in autonomous mode') elif opcode == self.spec.opcode_res_write_success: print('write success: addr=%s, data=%s' % (addr, data)) elif opcode == self.spec.opcode_res_write_error_mode: print('write error: controller in autonomous mode') elif opcode == self.spec.opcode_res_reset_success: print('reset success') elif opcode == self.spec.opcode_res_step_success: print('step success: cycle count=%s' % value) elif opcode == self.spec.opcode_res_step_error_mode: print('step error: controller in autonomous mode') elif opcode == self.spec.opcode_res_start_success: print('start success: cycle count at start=%s' % value) elif opcode == self.spec.opcode_res_start_error_mode: print('start error: already in autonomous mode') elif opcode == self.spec.opcode_res_pause_success: print('pause success: cycle_count=%s' % value) elif opcode == self.spec.opcode_res_pause_error_mode: print('pause error: already in manual mode') elif opcode == self.spec.opcode_res_status: print('status: cycle count=%s' % value) else: print('unable to read response: not connected') if __name__ == '__main__': FpgaEduShell().cmdloop()
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,922
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_controller.py
from myhdl import (Signal, ResetSignal, intbv, always, instance, Simulation, StopSimulation, delay, always_comb) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl import ClockGen, Controller def MockExperimentSetup(clk, reset, exp_addr, exp_din, exp_dout, exp_wen, exp_reset, exp_clk_en, initial={}): memory = dict(initial) @always(clk.posedge) def logic(): if exp_wen: memory[int(exp_addr.val)] = exp_din.val try: exp_dout.next = memory[int(exp_addr.val)] except KeyError: exp_dout.next = 2 return logic class ControllerTestCase(TestCase): HALF_PERIOD = 5 WIDTH_ADDR = 32 WIDTH_DATA = 8 MEM_INIT = { 3:4, 4:5, 5:6 } EXP_RESET_ACTIVE=False def setUp(self): self.spec = ControllerSpec(width_addr=self.WIDTH_ADDR, width_data=self.WIDTH_DATA) # Input signals self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.rx_msg = Signal(intbv(0)[self.spec.width_message:0]) self.rx_ready = Signal(False) self.tx_ready = Signal(True) self.exp_data_read = Signal(intbv(0)[self.spec.width_data:0]) # Output signals self.rx_next = Signal(False) self.tx_msg = Signal(intbv(0)[self.spec.width_message:0]) self.tx_next = Signal(False) self.exp_addr = Signal(intbv(0)[self.spec.width_addr:0]) self.exp_data_write = Signal(intbv(0)[self.spec.width_data:0]) self.exp_wen = Signal(False) self.exp_reset = ResetSignal(not self.EXP_RESET_ACTIVE, active=self.EXP_RESET_ACTIVE, async=False) self.exp_clk_en = Signal(False) self.clockgen = ClockGen(clk=self.clk, half_period=self.HALF_PERIOD) self.controller = Controller(spec=self.spec, clk=self.clk, reset=self.reset, rx_msg=self.rx_msg, rx_next=self.rx_next, rx_ready=self.rx_ready, tx_msg =self.tx_msg, tx_next=self.tx_next, tx_ready=self.tx_ready, exp_addr=self.exp_addr, exp_data_write=self.exp_data_write, exp_data_read=self.exp_data_read, exp_wen=self.exp_wen, exp_reset=self.exp_reset, exp_clk_en=self.exp_clk_en, exp_reset_active=self.EXP_RESET_ACTIVE) self.mock_experiment = MockExperimentSetup(self.clk, self.reset, self.exp_addr, self.exp_data_write, self.exp_data_read, self.exp_wen, self.exp_reset, self.exp_clk_en, self.MEM_INIT) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.controller, self.mock_experiment, *test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def assert_value_type_response(self, opcode_expected, value_expected): opcode_actual = self.spec.parse_opcode(self.tx_msg) value_actual = self.spec.parse_value(self.tx_msg) self.assertEquals(opcode_actual, opcode_expected) self.assertEquals(value_actual, value_expected) def assert_addr_type_response(self, opcode_expected, address_expected, data_expected): opcode_actual = self.spec.parse_opcode(self.tx_msg) addr_actual = self.spec.parse_addr(self.tx_msg) data_actual = self.spec.parse_data(self.tx_msg) self.assertEquals(opcode_actual, opcode_expected) self.assertEquals(addr_actual, addr_expected) self.assertEquals(data_actual, data_expected) def test_reset(self): @instance def test(): self.reset.next = self.reset.active yield self.clk.negedge self.assertFalse(self.rx_next) self.assertFalse(self.tx_next) self.assertEquals(self.exp_reset, self.EXP_RESET_ACTIVE) self.assertFalse(self.exp_wen) self.assertFalse(self.exp_clk_en) yield self.clk.negedge self.assertFalse(self.exp_clk_en) yield self.clk.negedge self.assertFalse(self.exp_clk_en) self.stop_simulation() self.simulate([test]) def test_cmd_read(self): opcode = self.spec.opcode_cmd_read cmd1 = self.spec.addr_type_message(opcode, 3, 0) cmd2 = self.spec.addr_type_message(opcode, 4, 0) expected1 = self.spec.addr_type_message( self.spec.opcode_res_read_success, 3, 4) expected2 = self.spec.addr_type_message( self.spec.opcode_res_read_success, 4, 5) @instance def test(): self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active yield self.clk.negedge self.assertFalse(self.tx_next) self.rx_msg.next = cmd1 self.rx_ready.next = True self.tx_ready.next = True yield delay(1) self.assertTrue(self.rx_next) yield self.clk.negedge self.assertEquals(self.tx_msg, expected1) self.assertTrue(self.tx_next) self.rx_msg.next = cmd2 self.rx_ready.next = True yield delay(1) self.assertTrue(self.rx_next) yield self.clk.negedge self.assertEquals(self.tx_msg, expected2) self.assertTrue(self.tx_next) self.rx_ready.next = False yield self.clk.negedge self.assertFalse(self.tx_next) self.stop_simulation() self.simulate([test]) def test_cmd_write(self): @instance def test(): self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active self.rx_ready.next = True self.rx_msg.next = self.spec.addr_type_message( self.spec.opcode_cmd_write, 88, 9) self.tx_ready.next = True yield delay(1) self.assertTrue(self.rx_next) self.assertTrue(self.exp_wen) self.assertEquals(self.exp_addr, 88) yield self.clk.negedge self.assertEquals(self.exp_data_read, 9) self.assertTrue(self.tx_next) self.assertEquals(self.exp_addr, 88) self.rx_ready.next = False yield delay(1) self.assertFalse(self.rx_next) self.assertFalse(self.exp_wen) yield self.clk.negedge self.assertFalse(self.tx_next) self.stop_simulation() self.simulate([test]) def test_cmd_reset(self): @instance def test(): self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active yield self.clk.negedge self.assertEquals(self.exp_reset, not self.EXP_RESET_ACTIVE) self.rx_msg.next = self.spec.value_type_message( self.spec.opcode_cmd_reset, 0) self.rx_ready.next = True self.tx_ready.next = True yield delay(1) self.assertEquals(self.exp_reset, self.EXP_RESET_ACTIVE) yield self.clk.negedge self.assertEquals(self.tx_msg, self.spec.value_type_message( self.spec.opcode_res_reset_success, 0)) self.stop_simulation() self.simulate([test]) def test_cmd_step(self): @instance def test(): self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active self.rx_ready.next = False self.tx_ready.next = True yield self.clk.posedge yield delay(1) self.assertFalse(self.exp_clk_en) self.rx_msg.next = self.spec.value_type_message( self.spec.opcode_cmd_step, 0) self.rx_ready.next = True yield delay(1) self.assertFalse(self.exp_clk_en) yield self.clk.negedge yield delay(1) self.assertTrue(self.exp_clk_en) self.assertFalse(self.tx_next) yield self.clk.posedge yield delay(1) self.assertTrue(self.exp_clk_en) self.assertTrue(self.tx_next) self.rx_ready.next = False yield self.clk.negedge yield delay(1) self.assertFalse(self.exp_clk_en) self.stop_simulation() self.simulate([test]) def test_cmd_start_pause(self): @instance def test(): self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active self.rx_ready.next = False self.tx_ready.next = True self.stop_simulation() self.simulate([test])
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,923
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/_clock_enable_buffer.py
from myhdl import always_comb def ClockEnableBuffer(clk_in, clk_out, clk_en): @always_comb def logic(): if clk_en: clk_out.next = clk_in else: clk_out.next = False clk_in.read = True clk_en.read = True clk_out.driven = True return logic ClockEnableBuffer.vhdl_code = \ ''' -- BUFGCE: Global Clock Buffer with Clock Enable -- 7 Series -- Xilinx HDL Libraries Guide, version 14.7 BUFGCE_inst : BUFGCE port map ( O => $clk_out, -- 1-bit output: Clock output CE => $clk_en, -- 1-bit input: Clock enable input for I0 I => $clk_in -- 1-bit input: Primary clock ); -- End of BUFGCE_inst instantiation ''' ClockEnableBuffer.verilog_code = \ ''' // BUFGCE: Global Clock Buffer with Clock Enable // 7 Series // Xilinx HDL Libraries Guide, version 14.7 BUFGCE BUFGCE_inst ( .O(O), // 1-bit output: Clock output .CE(CE), // 1-bit input: Clock enable input for I0 .I(I) // 1-bit input: Primary clock ); // End of BUFGCE_inst instantiation '''
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,924
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_controller_response_compose.py
from myhdl import always_comb def ControllerResponseCompose(spec, opcode_res, addr, data, nop, cycle_count, tx_ready, tx_next, tx_msg): ''' opcode_res: input signal addr: input signal data: input signal nop: input signal tx_ready: input signal tx_next: output signal ''' @always_comb def output_logic(): tx_next.next = False tx_msg.next = 0 if tx_ready and not nop: tx_next.next = True # set response opcode tx_msg.next[spec.index_opcode_high+1:spec.index_opcode_low] = \ opcode_res if (opcode_res == spec.opcode_res_read_success or opcode_res == spec.opcode_res_write_success): # addr-type response message tx_msg.next[spec.index_addr_high+1:spec.index_addr_low] = addr tx_msg.next[spec.index_data_high+1:spec.index_data_low] = data elif (opcode_res == spec.opcode_res_read_error_mode or opcode_res == spec.opcode_res_write_error_mode): # addr-type response message tx_msg.next[spec.index_addr_high+1:spec.index_addr_low] = addr tx_msg.next[spec.index_data_high+1:spec.index_data_low] = 0 elif (opcode_res == spec.opcode_res_step_success): tx_msg.next[spec.index_value_high+1:spec.index_value_low] = \ cycle_count + 1 elif (opcode_res == spec.opcode_res_start_success or opcode_res == spec.opcode_res_pause_success or opcode_res == spec.opcode_res_status): tx_msg.next[spec.index_value_high+1: spec.index_value_low] = cycle_count else: tx_msg.next[spec.index_value_high+1: spec.index_value_low] = 0 return output_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,925
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_message_transmitter.py
from myhdl import (enum, always_comb, always_seq, Signal, intbv, always) def MessageTransmitter(spec, clk, reset, tx_fifo_data_write, tx_fifo_full, tx_fifo_enqueue, message, ready, transmit_next): ''' Input signals: clk reset message tx_fifo_full transmit_next Output signals: tx_fifo_data_write tx_fifo_enqueue ready ''' state_t = enum('IDLE', 'TRANSMIT_START', 'TRANSMIT_STOP', 'TRANSMIT_DATA') state_reg = Signal(state_t.IDLE) state_next = Signal(state_t.IDLE) prev_esc_reg = Signal(False) prev_esc_next = Signal(False) message_reg = Signal(intbv(0)[spec.width_message_bytes*8:0]) message_next = Signal(intbv(0)[spec.width_message_bytes*8:0]) byte_count_reg = Signal(intbv(0, min=0, max=spec.width_message_bytes)) byte_count_next = Signal(intbv(0, min=0, max=spec.width_message_bytes)) index_low = Signal(intbv(0, min=0, max=8*spec.width_message_bytes+1)) dout = Signal(intbv(0)[8:0]) esc = Signal(False) @always_seq(clk.posedge, reset=reset) def register_logic(): state_reg.next = state_next prev_esc_reg.next = prev_esc_next message_reg.next = message_next byte_count_reg.next = byte_count_next @always_comb def next_state_logic(): state_next.next = state_reg prev_esc_next.next = prev_esc_reg message_next.next = message_reg byte_count_next.next = byte_count_reg if state_reg == state_t.IDLE: if transmit_next: state_next.next = state_t.TRANSMIT_START message_next.next[8*spec.width_message_bytes:spec.width_message] = 0 message_next.next[spec.width_message:0] = message elif state_reg == state_t.TRANSMIT_START: if not tx_fifo_full: byte_count_next.next = 0 state_next.next = state_t.TRANSMIT_DATA elif state_reg == state_t.TRANSMIT_DATA: if not tx_fifo_full and esc and not prev_esc_reg: prev_esc_next.next = True elif not tx_fifo_full and (not esc or (esc and prev_esc_reg)): byte_count_next.next = (byte_count_reg+1) % \ spec.width_message_bytes prev_esc_next.next = False if byte_count_reg == spec.width_message_bytes - 1: state_next.next = state_t.TRANSMIT_STOP elif state_reg == state_t.TRANSMIT_STOP: if not tx_fifo_full: state_next.next = state_t.IDLE @always_comb def index_logic(): index_low.next = 8*spec.width_message_bytes-byte_count_reg*8-8 @always_comb def dout_logic(): #dout.next = message_reg[index_high:index_low] dout.next[0] = message_reg[index_low+0] dout.next[1] = message_reg[index_low+1] dout.next[2] = message_reg[index_low+2] dout.next[3] = message_reg[index_low+3] dout.next[4] = message_reg[index_low+4] dout.next[5] = message_reg[index_low+5] dout.next[6] = message_reg[index_low+6] dout.next[7] = message_reg[index_low+7] @always_comb def esc_logic(): esc.next = (dout == spec.chr_start or dout == spec.chr_esc or dout == spec.chr_stop) @always_comb def output_logic(): tx_fifo_enqueue.next = (state_reg != state_t.IDLE and not tx_fifo_full) ready.next = (state_reg == state_t.IDLE) if state_reg == state_t.IDLE: tx_fifo_data_write.next = 0 elif state_reg == state_t.TRANSMIT_START: tx_fifo_data_write.next = spec.chr_start elif state_reg == state_t.TRANSMIT_DATA: if not esc or (esc and prev_esc_reg): tx_fifo_data_write.next = dout else: tx_fifo_data_write.next = spec.chr_esc elif state_reg == state_t.TRANSMIT_STOP: tx_fifo_data_write.next = spec.chr_stop return (register_logic, next_state_logic, output_logic, dout_logic, esc_logic, index_logic)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,926
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_baudgen.py
from myhdl import always_seq, always_comb, Signal, intbv from math import ceil from fpgaedu.hdl import Rom def BaudGen(clk, reset, rx_tick, tx_tick, clk_freq=100000000, baudrate=9600, rx_div=16): """ rss232 standard baud rates 300 1200 2400 4800 9600 14400 19200 28800 38400 57600 115200 230400 """ tx_tick_max = int(round(clk_freq/baudrate)) tick_count_reg = Signal(intbv(0, min=0, max=tx_tick_max)) tick_count_next = Signal(intbv(0, min=0, max=tx_tick_max)) rx_div_count_reg = Signal(intbv(0, min=0, max=rx_div)) rx_div_count_next = Signal(intbv(0, min=0, max=rx_div)) def calculate_rx_lookup_table(): ''' A lookup table is used to allow for synchronization between rx_tick and tx_tick ''' rx_tick_div = float(tx_tick_max)/float(rx_div) rx_tick_tbl = [0 for i in range(rx_div)] for i in range(rx_div): rx_tick_tbl[i] = int(round(float(i+1)*rx_tick_div)) - 1 return tuple(rx_tick_tbl) rx_tick_lookup_rom_dout = Signal(intbv(0, min=0, max=tx_tick_max)) rx_tick_lookup = calculate_rx_lookup_table() # myhdl requires the rom to be a separate instance in order to support # export to vhdl rx_tick_lookup_rom = Rom(dout=rx_tick_lookup_rom_dout, addr=rx_div_count_reg, content=rx_tick_lookup) # Register logic @always_seq(clk.posedge, reset) def reg_logic(): tick_count_reg.next = tick_count_next rx_div_count_reg.next = rx_div_count_next # Next state logic @always_comb def next_state_logic(): tick_count_next.next = (tick_count_reg + 1) % tx_tick_max if tick_count_reg == rx_tick_lookup_rom_dout: rx_div_count_next.next = (rx_div_count_reg + 1) % rx_div else: rx_div_count_next.next = rx_div_count_reg # Output logic @always_comb def output_logic(): if tick_count_reg == rx_tick_lookup_rom_dout: rx_tick.next = True else: rx_tick.next = False if tick_count_reg == (tx_tick_max - 1): tx_tick.next = True else: tx_tick.next = False return reg_logic, next_state_logic, output_logic, rx_tick_lookup_rom
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,927
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_controller_cycle_control.py
from myhdl import always_seq, always_comb, enum, Signal, intbv def ControllerCycleControl(spec, clk, reset, start, pause, step, cycle_autonomous, cycle_count, exp_clk_en): ''' spec: Controller spec clk: Input reset: Input start: Input pause: Input step: Input autonomous: Output cycle_count: Output exp_clk_en: Output ''' state_t = enum('MANUAL', 'AUTONOMOUS') state_reg = Signal(state_t.MANUAL) state_next = Signal(state_t.MANUAL) cycle_count_reg = Signal(intbv(0)[spec.width_value:0]) cycle_count_next = Signal(intbv(0)[spec.width_value:0]) exp_clk_en_reg = Signal(False) exp_clk_en_next = Signal(False) @always_seq(clk.negedge, reset) def register_logic(): state_reg.next = state_next cycle_count_reg.next = cycle_count_next exp_clk_en_reg.next = exp_clk_en_next @always_comb def next_state_logic(): state_next.next = state_reg cycle_count_next.next = cycle_count_reg exp_clk_en_next.next = False if state_reg == state_t.MANUAL: if step: cycle_count_next.next = cycle_count_reg + 1 exp_clk_en_next.next = True elif start: cycle_count_next.next = cycle_count_reg + 1 state_next.next = state_t.AUTONOMOUS exp_clk_en_next.next = True elif state_reg == state_t.AUTONOMOUS: if pause: exp_clk_en_next.next = False state_next.next = state_t.MANUAL else: exp_clk_en_next.next = True cycle_count_next.next = cycle_count_reg + 1 @always_comb def output_logic(): cycle_autonomous.next = (state_reg == state_t.AUTONOMOUS) cycle_count.next = cycle_count_reg exp_clk_en.next = exp_clk_en_reg return register_logic, next_state_logic, output_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,928
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_rom.py
from myhdl import always_comb def Rom(dout, addr, content): ''' http://docs.myhdl.org/en/stable/manual/conversion_examples.html#rom-inference ''' @always_comb def read(): dout.next = content[int(addr)] return read
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,929
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_uart_rx.py
from myhdl import (always_comb, always_seq, Signal, enum, intbv, now) def UartRx(clk, reset, rx, rx_data, rx_finish, rx_busy, rx_baud_tick, data_bits=8, stop_bits=1, rx_div=16): ''' clk input Clock Signal reset Input Reset Signal rx Input Uart Rx rx_data Output Reveived data rx_finish Output Pulse signal indicating that rx_data is ready rx_busy Output Indicating that the uart is receiving data rx_baud_tick Input Buadgen input rx_div Parameter Specifying the number of subsamples per tx_tick ''' state_t = enum('WAIT_START', 'RECV_START', 'RECV_DATA', 'RECV_STOP') state_reg = Signal(state_t.WAIT_START) state_next = Signal(state_t.WAIT_START) baud_count_reg = Signal(intbv(0, min=0, max=rx_div)) baud_count_next = Signal(intbv(0, min=0, max=rx_div)) data_reg = Signal(intbv(0)[data_bits:0]) data_next = Signal(intbv(0)[data_bits:0]) data_count_reg = Signal(intbv(0, min=0, max=data_bits)) data_count_next = Signal(intbv(0, min=0, max=data_bits)) LVL_HIGH = True LVL_LOW = False LVL_START = LVL_LOW LVL_STOP = LVL_HIGH LVL_IDLE = LVL_HIGH @always_seq(clk.posedge, reset) def register_logic(): state_reg.next = state_next baud_count_reg.next = baud_count_next data_count_reg.next = data_count_next data_reg.next = data_next @always_comb def next_state_logic(): ''' Determine next state levels for registers state_reg, baud_count_reg, data_count_reg and data_reg based on current state and input signals ''' rx_finish.next = False rx_data.next = 0 state_next.next = state_reg baud_count_next.next = baud_count_reg data_next.next = data_reg data_count_next.next = data_count_reg if state_reg == state_t.WAIT_START: data_next.next = 0 if rx == LVL_START and rx_baud_tick == True: state_next.next = state_t.RECV_START elif state_reg == state_t.RECV_START: if rx_baud_tick == True: baud_count_next.next = (baud_count_reg + 1) % int(rx_div/2) if baud_count_reg == int(rx_div/2) - 1: state_next.next = state_t.RECV_DATA elif state_reg == state_t.RECV_DATA: if rx_baud_tick == 1: baud_count_next.next = (baud_count_reg + 1) % rx_div if baud_count_reg == rx_div - 1: data_count_next.next = (data_count_reg + 1) % data_bits data_next.next[data_count_reg] = rx if data_count_reg == data_bits - 1: state_next.next = state_t.RECV_STOP elif state_reg == state_t.RECV_STOP: if rx_baud_tick == True: baud_count_next.next = (baud_count_reg + 1) % rx_div if baud_count_reg == rx_div - 1: state_next.next = state_t.WAIT_START if rx == LVL_STOP: rx_data.next = data_reg rx_finish.next = True @always_comb def output_logic(): """ Determine levels for output signals rx_data, rx_finish, rx_busy based on input signals and current register states """ if state_reg == state_t.WAIT_START: rx_busy.next = False else: rx_busy.next = True return register_logic, next_state_logic, output_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,930
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_message_receiver.py
from myhdl import (enum, always_comb, always_seq, Signal, intbv, always) def MessageReceiver(spec, clk, reset, rx_fifo_data_read, rx_fifo_empty, rx_fifo_dequeue, message, message_ready, receive_next): ''' Input signals: clk reset rx_fifo_data_read rx_fifo_empty receive_next Output signals: rx_fifo_dequeue message message_ready ''' state_t = enum('READ_START', 'READ_DATA', 'READ_STOP', 'READY') state_reg = Signal(state_t.READ_START) state_next = Signal(state_t.READ_START) esc_reg = Signal(False) esc_next = Signal(False) message_reg = Signal(intbv(0)[spec.width_message_bytes*8:0]) message_next = Signal(intbv(0)[spec.width_message_bytes*8:0]) byte_count_reg = Signal(intbv(0, min=0, max=spec.width_message_bytes)) byte_count_next = Signal(intbv(0, min=0, max=spec.width_message_bytes)) index_low = Signal(intbv(0, min=0, max=8*spec.width_message_bytes+1)) @always_seq(clk.posedge, reset=reset) def register_logic(): state_reg.next = state_next esc_reg.next = esc_next message_reg.next = message_next byte_count_reg.next = byte_count_next @always_comb def index_logic(): index_low.next = 8*spec.width_message_bytes - byte_count_reg*8 -8 @always_comb def next_state_logic(): state_next.next = state_reg message_next.next = message_reg byte_count_next.next = byte_count_reg esc_next.next = not rx_fifo_empty and rx_fifo_data_read == spec.chr_esc if state_reg == state_t.READ_START: if rx_fifo_data_read == spec.chr_start and not rx_fifo_empty and \ not esc_reg: state_next.next = state_t.READ_DATA elif state_reg == state_t.READ_DATA: if not esc_reg and rx_fifo_data_read == spec.chr_start: byte_count_next.next = 0 elif not esc_reg and rx_fifo_data_read == spec.chr_stop: byte_count_next.next = 0 state_next.next = state_t.READ_START elif (not esc_reg and not rx_fifo_empty and rx_fifo_data_read != \ spec.chr_esc) or (esc_reg and not rx_fifo_empty): byte_count_next.next = (byte_count_reg + 1) % \ spec.width_message_bytes message_next.next[index_low+0] = rx_fifo_data_read[0] message_next.next[index_low+1] = rx_fifo_data_read[1] message_next.next[index_low+2] = rx_fifo_data_read[2] message_next.next[index_low+3] = rx_fifo_data_read[3] message_next.next[index_low+4] = rx_fifo_data_read[4] message_next.next[index_low+5] = rx_fifo_data_read[5] message_next.next[index_low+6] = rx_fifo_data_read[6] message_next.next[index_low+7] = rx_fifo_data_read[7] if byte_count_reg == spec.width_message_bytes-1: state_next.next = state_t.READ_STOP elif state_reg == state_t.READ_STOP: if rx_fifo_data_read == spec.chr_stop and not rx_fifo_empty and \ not esc_reg: state_next.next = state_t.READY elif state_reg == state_t.READY: if receive_next: state_next.next = state_t.READ_START @always_comb def output_logic(): message.next = message_reg[spec.width_message:0] message_ready.next = state_reg == state_t.READY if state_reg == state_t.READY: rx_fifo_dequeue.next = False else: rx_fifo_dequeue.next = not rx_fifo_empty return register_logic, next_state_logic, output_logic, index_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,931
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/_board_component.py
from myhdl import Signal, intbv, always_comb from fpgaedu import ControllerSpec from fpgaedu.hdl import (Controller, UartRx, UartTx, BaudGen, Fifo, MessageReceiver, MessageTransmitter) from ._clock_enable_buffer import ClockEnableBuffer from ._board_component_tx import BoardComponentTx from ._board_component_rx import BoardComponentRx #from fpgaedu.hdl.nexys4 import (ClockEnableBuffer, BoardComponentRx, # BoardComponentTx) _CLK_FREQ = 100000000 _RX_DIV = 8 _TX_FIFO_DEPTH = 16 _RX_FIFO_DEPTH = 16 _DATA_BITS=8 _STOP_BITS=1 def BoardComponent(spec, clk, reset, rx, tx, exp_addr, exp_data_write, exp_data_read, exp_wen, exp_reset, exp_clk, exp_clk_en, exp_reset_active=True, baudrate=9600): tx_baud_tick = Signal(False) rx_baud_tick = Signal(False) exp_clk_en_internal = Signal(False) message_rx_data = Signal(intbv(0)[spec.width_message:0]) message_rx_ready = Signal(False) message_rx_recv_next = Signal(False) message_tx_data = Signal(intbv(0)[spec.width_message:0]) message_tx_ready = Signal(False) message_tx_trans_next = Signal(False) controller = Controller(spec=spec, clk=clk, reset=reset, rx_msg=message_rx_data, rx_next=message_rx_recv_next, rx_ready=message_rx_ready, tx_msg=message_tx_data, tx_next=message_tx_trans_next, tx_ready= message_tx_ready, exp_addr=exp_addr, exp_data_write=exp_data_write, exp_data_read=exp_data_read, exp_wen=exp_wen, exp_reset=exp_reset, exp_clk_en=exp_clk_en_internal, exp_reset_active=exp_reset_active) component_rx = BoardComponentRx(spec=spec, clk=clk, reset=reset, rx=rx, rx_msg=message_rx_data, rx_ready=message_rx_ready, rx_next=message_rx_recv_next, uart_rx_baud_tick=rx_baud_tick, uart_rx_baud_div=_RX_DIV) component_tx = BoardComponentTx(spec=spec, clk=clk, reset=reset, tx=tx, tx_msg=message_tx_data, tx_ready=message_tx_ready, tx_next=message_tx_trans_next, uart_tx_baud_tick=tx_baud_tick) baudgen = BaudGen(clk=clk, reset=reset, rx_tick=rx_baud_tick, tx_tick=tx_baud_tick, baudrate=baudrate, rx_div=_RX_DIV) clock_enable_buffer = ClockEnableBuffer(clk_in=clk, clk_out=exp_clk, clk_en=exp_clk_en_internal) @always_comb def expose_exp_clk_en(): exp_clk_en.next = exp_clk_en_internal return (controller, baudgen, clock_enable_buffer, component_rx, component_tx, expose_exp_clk_en)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,932
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_message_transmitter.py
from myhdl import (Signal, ResetSignal, intbv, always, instance, Simulation, StopSimulation, delay, always_comb) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl import ClockGen, MessageTransmitter class MessageTransmitterTestCase(TestCase): HALF_PERIOD = 5 WIDTH_ADDR = 32 WIDTH_DATA = 8 def setUp(self): self.spec = ControllerSpec(self.WIDTH_ADDR, self.WIDTH_DATA) # Input signals self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.message = Signal(intbv(0)[self.spec.width_message:0]) self.tx_fifo_full = Signal(False) self.transmit_next = Signal(False) # Output signals self.tx_fifo_data_write = Signal(intbv(0)[8:0]) self.tx_fifo_enqueue = Signal(False) self.ready = Signal(False) self.clockgen = ClockGen(self.clk, self.HALF_PERIOD) self.transmitter = MessageTransmitter(spec=self.spec, clk=self.clk, reset=self.reset, tx_fifo_data_write=self.tx_fifo_data_write, tx_fifo_full=self.tx_fifo_full, tx_fifo_enqueue=self.tx_fifo_enqueue, message=self.message, ready=self.ready, transmit_next=self.transmit_next) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.transmitter, *test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_transmit(self): @instance def test(): yield delay(10) self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active yield self.clk.negedge self.assertTrue(self.ready) self.assertFalse(self.tx_fifo_enqueue) self.message.next = 0xF221244557D self.tx_fifo_full.next = False self.transmit_next.next = True yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, self.spec.chr_start) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x0F) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x22) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, self.spec.chr_esc) self.tx_fifo_full.next = True yield self.clk.negedge yield self.clk.negedge yield self.clk.negedge yield self.clk.negedge yield self.clk.negedge self.assertFalse(self.ready) self.assertFalse(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, self.spec.chr_esc) self.tx_fifo_full.next = False yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x12) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x44) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x55) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x7D) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, 0x7D) yield self.clk.negedge self.assertFalse(self.ready) self.assertTrue(self.tx_fifo_enqueue) self.assertEquals(self.tx_fifo_data_write, self.spec.chr_stop) self.stop_simulation() self.simulate([test])
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,933
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/_test_setup.py
from myhdl import Signal, intbv from fpgaedu.hdl.nexys4 import BoardComponent from fpgaedu.hdl.testexperiment._wrapper_composition import WrapperComposition def TestSetup(spec, clk, reset, rx, tx): exp_addr = Signal(intbv(0)[spec.width_addr:0]) exp_din = Signal(intbv(0)[spec.width_data:0]) exp_dout = Signal(intbv(0)[spec.width_data:0]) exp_wen = Signal(False) exp_reset = Signal(False) exp_clk = Signal(False) board_component = BoardComponent(spec, clk, reset, rx, tx, exp_addr, exp_din, exp_dout, exp_wen, exp_reset, exp_clk, exp_reset_active=True, baudrate=9600) # test_experiment = TestExperiment(exp_clk, exp_reset, exp_addr, exp_din, # exp_dout, exp_wen) wrapper = WrapperComposition(clk=clk, exp_clk=exp_clk, exp_reset=exp_reset, din=exp_din, dout=exp_dout, addr=exp_addr, wen=exp_wen) return board_component, wrapper
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,934
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_fifo.py
from myhdl import now, Signal, intbv, always_seq, always_comb, always #from math import log2, ceil from fpgaedu.hdl import Ram def Fifo(clk, reset, din, enqueue, dout, dequeue, empty, full, data_width=8, depth=16): ''' clk Input clock signal reset Input reset signal din Data in input signal enqueue Input signal that adds the data on din to the buffer dout Data out output signal. if empty, dout = 0. If not empty, dout is always set to the value of the oldest item in the buffer dequeue Removes the oldest item from the buffer and sets dout to be the next- oldest value empty Output signal indicating that the fifo is empty full Output signal indicating that the fifo is full ''' #addr_width = int(ceil(log2(depth))) oldest_addr_reg = Signal(intbv(0, min=0, max=depth)) oldest_addr_next = Signal(intbv(0, min=0, max=depth)) count_reg = Signal(intbv(0, min=0, max=depth+1)) count_next = Signal(intbv(0, min=0, max=depth+1)) #ram_addr = Signal(intbv(0)[addr_width:0]) #ram = Ram(clk=clk, dout=dout, din=din, addr=ram_addr, wen=wen, # data_width=data_width, depth=depth) mem = [Signal(intbv(0)[data_width:]) for i in range(depth)] @always_seq(clk.posedge, reset) def register_logic(): oldest_addr_reg.next = oldest_addr_next count_reg.next = count_next if dequeue: oldest_addr_next.next = (oldest_addr_reg + 1) % depth else: oldest_addr_next.next = oldest_addr_reg if enqueue and not dequeue: if not(count_reg == depth): count_next.next = count_reg + 1 mem[(oldest_addr_reg + count_reg) % depth].next = din elif not enqueue and dequeue: if count_reg == 0: count_next.next = count_reg else: count_next.next = count_reg - 1 else: count_next.next = count_reg @always_comb def output_logic(): empty.next = False full.next = False if count_reg == 0: dout.next = 0 else: dout.next = mem[oldest_addr_reg] if count_reg == 0: empty.next = True elif count_reg == depth: full.next = True #return register_logic, next_state_logic, output_logic return register_logic, output_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,935
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_controller_cycle_control.py
from myhdl import (Signal, ResetSignal, intbv, always, instance, Simulation, StopSimulation, delay) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl import ClockGen from fpgaedu.hdl._controller_cycle_control import ControllerCycleControl class ControllerCycleControlTestCase(TestCase): WIDTH_ADDR = 32 WIDTH_DATA = 8 HALF_PERIOD = 5 def setUp(self): self.spec = ControllerSpec(self.WIDTH_ADDR, self.WIDTH_DATA) #input signals self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.start = Signal(False) self.pause = Signal(False) self.step = Signal(False) #output signals self.autonomous = Signal(False) self.cycle_count = Signal(intbv(0)[self.spec.width_value:0]) self.exp_clk_en = Signal(False) #instances self.clockgen = ClockGen(self.clk, self.HALF_PERIOD) self.cycle_control = ControllerCycleControl(spec=self.spec, clk=self.clk, reset=self.reset, start=self.start, pause=self.pause, step=self.step, cycle_autonomous=self.autonomous, cycle_count=self.cycle_count, exp_clk_en=self.exp_clk_en) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.cycle_control, test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_cycle_control_step(self): @instance def test_method(): self.reset.next = False yield self.clk.negedge self.reset.next = True self.start.next = False self.pause.next = False self.step.next = False yield self.clk.posedge self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 0) self.assertFalse(self.exp_clk_en) self.step.next = True yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 1) self.assertTrue(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.step.next = False yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 1) self.assertFalse(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.step.next = True yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 2) self.assertTrue(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.step.next = False yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 2) self.assertFalse(self.exp_clk_en) self.stop_simulation() self.simulate(test_method) def test_cycle_control_start_pause(self): @instance def test(): self.reset.next = False yield self.clk.negedge yield self.clk.posedge self.reset.next = True self.start.next = False self.pause.next = False self.step.next = False yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 0) self.assertFalse(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.start.next = True yield self.clk.negedge yield delay(1) self.assertTrue(self.autonomous) self.assertEquals(self.cycle_count, 1) self.assertTrue(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.start.next = False yield self.clk.negedge yield delay(1) self.assertTrue(self.autonomous) self.assertEquals(self.cycle_count, 2) self.assertTrue(self.exp_clk_en) yield self.clk.negedge yield delay(1) self.assertTrue(self.autonomous) self.assertEquals(self.cycle_count, 3) self.assertTrue(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.pause.next = True yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 3) self.assertFalse(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.pause.next = False yield self.clk.negedge yield delay(1) self.assertFalse(self.autonomous) self.assertEquals(self.cycle_count, 3) self.assertFalse(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.start.next = True yield self.clk.negedge yield delay(1) self.assertTrue(self.autonomous) self.assertEquals(self.cycle_count, 4) self.assertTrue(self.exp_clk_en) yield self.clk.posedge yield delay(1) self.start.next = False yield self.clk.negedge yield delay(1) self.assertTrue(self.autonomous) self.assertEquals(self.cycle_count, 5) self.assertTrue(self.exp_clk_en) self.stop_simulation() self.simulate(test)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,936
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/__init__.py
from ._controllerspec import ControllerSpec
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,937
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/generate_vhdl.py
import os, sys, argparse from myhdl import toVHDL, toVerilog, Signal, ResetSignal, intbv from fpgaedu import ControllerSpec from fpgaedu.hdl.nexys4 import BoardComponent _UART_BAUDRATE = 9600 # NEXYS 4 board reset signal is active-low _RESET_ACTIVE = False def _parse_args(): ''' Parses the command line arguments. ''' parser = argparse.ArgumentParser(description='Generates digilent nexys \ board component vhdl source files.') parser.add_argument('-o', '--outputDir', required=True, help='The source file output directory.'); parser.add_argument('-a', '--addressWidth', required=True, type=int) parser.add_argument('-d', '--dataWidth', required=True, type=int) parser.add_argument('-t', '--topLevel', required=True, help='The output top-level file\'s file name.') parser.add_argument('-r', '--resetActive', required=True, type=bool, help='Whether the experiment setup reset is active-high ("True") or \ active-low ("False").') return parser.parse_args() def _generate_vhdl(output_dir, width_addr, width_data, top_level_file_name, \ exp_reset_active): toVHDL.std_logic_ports = True toVHDL.name = os.path.splitext(top_level_file_name)[0] toVHDL.directory = output_dir toVHDL.use_clauses = \ ''' Library UNISIM; use UNISIM.vcomponents.all; use work.pck_myhdl_090.all; ''' spec = ControllerSpec(width_addr, width_data) clk = Signal(False) reset = ResetSignal(not _RESET_ACTIVE, active=_RESET_ACTIVE, async=False) rx = Signal(False) tx = Signal(False) exp_addr = Signal(intbv(0)[width_addr:0]) exp_din = Signal(intbv(0)[width_data:0]) exp_dout = Signal(intbv(0)[width_data:0]) exp_wen = Signal(False) exp_reset = Signal(False) exp_clk = Signal(False) exp_clk_en = Signal(False) toVHDL(BoardComponent, spec=spec, clk=clk, reset=reset, rx=rx, tx=tx, exp_addr=exp_addr, exp_data_write=exp_din, exp_data_read=exp_dout, exp_wen=exp_wen, exp_reset=exp_reset, exp_clk=exp_clk, exp_clk_en=exp_clk_en, exp_reset_active=exp_reset_active, baudrate=_UART_BAUDRATE) if __name__ == '__main__': args = _parse_args() _generate_vhdl(args.outputDir, args.addressWidth, args.dataWidth, args.topLevel, args.resetActive)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,938
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_baudgen.py
from myhdl import (Signal, ResetSignal, intbv, Simulation, StopSimulation, instance, delay, now, traceSignals) from math import ceil import unittest from unittest import TestCase from random import randint from fpgaedu.hdl import BaudGen, ClockGen class BaudGenTestCase(TestCase): BAUDRATE = 230401 CLK_FREQ = 100000000 RX_DIV = 16 CLK_HALF_PERIOD = 1 def setUp(self): self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.rx_tick = Signal(False) self.tx_tick = Signal(False) self.clockgen = ClockGen(self.clk, self.CLK_HALF_PERIOD) self.baudgen = BaudGen(self.clk, self.reset, self.rx_tick, self.tx_tick, clk_freq=self.CLK_FREQ, baudrate=self.BAUDRATE, rx_div=self.RX_DIV) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.baudgen, test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_tx_tick(self): ''' Test that a subsequent tx_tick is properly delayed ''' delta_tick = int(ceil(self.CLK_FREQ / self.BAUDRATE)) delta_tick = delta_tick * 2 @instance def test(): self.reset.next = False yield self.clk.negedge self.reset.next = True yield self.tx_tick.posedge prev_now = curr_now = now() # Test 5 subsequent cycles for j in range(3): yield self.tx_tick.posedge curr_now = now() delta_now = curr_now - prev_now delta = abs(delta_now - delta_tick) self.assertTrue(delta == 0, 'delta = %s, should max 0 (0 clock cycles)' % delta) prev_now = curr_now self.stop_simulation() self.simulate(test) def test_rx_tick(self): ''' test that a subsequent rx_tick has a maximum deviation of 1 clock cycle, due to float rounding ''' delta_tick = self.CLK_FREQ / (self.BAUDRATE * self.RX_DIV) delta_tick = delta_tick * 2 @instance def test(): self.reset.next = False yield self.clk.negedge self.reset.next = True yield self.rx_tick.posedge prev_now = curr_now = now() # run 3 tx cycles = 3 * rx_div for i in range(3 * self.RX_DIV): yield self.rx_tick.posedge curr_now = now() delta_now = curr_now - prev_now delta = abs(delta_now - delta_tick) self.assertTrue(delta <= 2, 'delta = %s, should max 2 (1 clock cycle)' % delta) prev_now = curr_now self.stop_simulation() self.simulate(test) def test_rx_tx_sync(self): ''' Check that the tx_tick and rx_tick signals are in sync when tx_tick is high. ''' tx_div = int(ceil(self.CLK_FREQ / self.BAUDRATE)) @instance def test(): for j in range(5): yield self.tx_tick.posedge self.assertTrue(self.tx_tick) self.assertEquals(self.rx_tick, self.tx_tick) self.stop_simulation() self.simulate(test) if __name__ == '__main__': unittest.main()
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,939
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/__init__.py
from ._clock_enable_buffer import ClockEnableBuffer from ._board_component import BoardComponent from ._board_component_rx import BoardComponentRx from ._board_component_tx import BoardComponentTx
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,940
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_message_receiver.py
from myhdl import (Signal, ResetSignal, intbv, always, instance, Simulation, StopSimulation, delay, always_comb) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl import ClockGen, MessageReceiver class MessageReceiverTestCase(TestCase): HALF_PERIOD = 5 WIDTH_ADDR = 32 WIDTH_DATA = 8 def setUp(self): self.spec = ControllerSpec(self.WIDTH_ADDR, self.WIDTH_DATA) # Input signals self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.rx_fifo_data_read = Signal(intbv(0)[8:0]) self.rx_fifo_empty = Signal(False) self.receive_next = Signal(False) # Output signals self.message = Signal(intbv(0)[self.spec.width_message:0]) self.rx_fifo_dequeue = Signal(False) self.message_ready = Signal(False) self.clockgen = ClockGen(self.clk, self.HALF_PERIOD) self.receiver = MessageReceiver(spec=self.spec, clk=self.clk, reset=self.reset, rx_fifo_data_read=self.rx_fifo_data_read, rx_fifo_empty=self.rx_fifo_empty, rx_fifo_dequeue=self.rx_fifo_dequeue, message=self.message, message_ready=self.message_ready, receive_next=self.receive_next) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.receiver, *test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_message(self): @instance def test(): yield self.clk.negedge self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active self.receive_next.next = False self.rx_fifo_empty.next = True self.rx_fifo_data_read.next = 0 yield self.clk.negedge self.assertFalse(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = 0 yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = self.spec.chr_start yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = 0xAA yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = 0xFF yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = 0xFF yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = self.spec.chr_esc yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = self.spec.chr_start yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = 0xFF yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = 0xAF yield self.clk.negedge self.assertTrue(self.rx_fifo_dequeue) self.assertFalse(self.message_ready) self.rx_fifo_empty.next = False self.rx_fifo_data_read.next = self.spec.chr_stop yield self.clk.negedge self.assertFalse(self.rx_fifo_dequeue) self.assertTrue(self.message_ready) self.assertEquals(self.message, 0xAFFFF12FFAF) self.stop_simulation() self.simulate([test])
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,941
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_controller_response_compose.py
from myhdl import (Signal, intbv, always, instance, Simulation, StopSimulation, delay) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl._controller_response_compose import ControllerResponseCompose class ControllerResponseComposeTestCase(TestCase): WIDTH_ADDR = 32 WIDTH_DATA = 8 def setUp(self): self.spec = ControllerSpec(self.WIDTH_ADDR, self.WIDTH_DATA) #input signals self.opcode_res = Signal(intbv(0)[self.spec.width_opcode:0]) self.addr = Signal(intbv(0)[self.spec.width_addr:0]) self.data = Signal(intbv(0)[self.spec.width_data:0]) self.nop = Signal(False) self.tx_ready = Signal(False) self.cycle_count = Signal(intbv(0)[self.spec.width_value:0]) # Output signals self.tx_next = Signal(False) self.tx_msg = Signal(intbv(0)[self.spec.width_message:0]) self.response_compose = ControllerResponseCompose(spec=self.spec, opcode_res=self.opcode_res, addr=self.addr, data=self.data, nop=self.nop, cycle_count=self.cycle_count, tx_ready=self.tx_ready, tx_next=self.tx_next, tx_msg=self.tx_msg) def simulate(self, test_logic, duration=None): sim = Simulation(self.response_compose, test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def assert_value_type_response(self, opcode_expected, value_expected): opcode_actual = self.spec.parse_opcode(self.tx_msg.val) value_actual = self.spec.parse_value(self.tx_msg.val) self.assertEquals(opcode_actual, opcode_expected) self.assertEquals(value_actual, value_expected) def assert_addr_type_response(self, opcode_expected, addr_expected, data_expected): opcode_actual = self.spec.parse_opcode(self.tx_msg.val) addr_actual = self.spec.parse_addr(self.tx_msg.val) data_actual = self.spec.parse_data(self.tx_msg.val) self.assertEquals(opcode_actual, opcode_expected) self.assertEquals(addr_actual, addr_expected) self.assertEquals(data_actual, data_expected) def test_tx_next(self): @instance def test(): yield delay(1) self.nop.next = True self.tx_ready.next = False yield delay(1) self.assertFalse(self.tx_next) self.nop.next = True self.tx_ready.next = True yield delay(1) self.assertFalse(self.tx_next) self.nop.next = False self.tx_ready.next = False yield delay(1) self.assertFalse(self.tx_next) self.nop.next = False self.tx_ready.next = True yield delay(1) self.assertTrue(self.tx_next) self.stop_simulation() self.simulate(test) def test_tx_msg(self): @instance def test(): self.nop.next = False self.tx_ready.next = True # read success self.addr.next = 23 self.data.next = 3 self.opcode_res.next = self.spec.opcode_res_read_success yield delay(10) self.assert_addr_type_response(self.spec.opcode_res_read_success, 23, 3) # read error self.opcode_res.next = self.spec.opcode_res_read_error_mode yield delay(1) self.assert_addr_type_response( self.spec.opcode_res_read_error_mode, 23, 0) # write success self.addr.next = 26 self.data.next = 6 self.opcode_res.next = self.spec.opcode_res_write_success yield delay(10) self.assert_addr_type_response(self.spec.opcode_res_write_success, 26, 6) # read error self.opcode_res.next = self.spec.opcode_res_write_error_mode yield delay(1) self.assert_addr_type_response( self.spec.opcode_res_write_error_mode, 26, 0) # reset success self.opcode_res.next = self.spec.opcode_res_reset_success yield delay(1) self.assert_value_type_response( self.spec.opcode_res_reset_success, 0) # Step success self.cycle_count.next = 34523 self.opcode_res.next = self.spec.opcode_res_step_success yield delay(1) self.assert_value_type_response( self.spec.opcode_res_step_success, 34524) # Step error self.opcode_res.next = self.spec.opcode_res_step_error_mode yield delay(1) self.assert_value_type_response( self.spec.opcode_res_step_error_mode, 0) # Start success self.cycle_count.next = 3523 self.opcode_res.next = self.spec.opcode_res_start_success yield delay(1) self.assert_value_type_response( self.spec.opcode_res_start_success, 3523) # Start error self.opcode_res.next = self.spec.opcode_res_start_error_mode yield delay(1) self.assert_value_type_response( self.spec.opcode_res_start_error_mode, 0) # Pause success self.cycle_count.next = 823 self.opcode_res.next = self.spec.opcode_res_pause_success yield delay(1) self.assert_value_type_response( self.spec.opcode_res_pause_success, 823) # Pause error self.opcode_res.next = self.spec.opcode_res_pause_error_mode yield delay(1) self.assert_value_type_response( self.spec.opcode_res_pause_error_mode, 0) # Status self.cycle_count.next = 11823 self.opcode_res.next = self.spec.opcode_res_status yield delay(1) self.assert_value_type_response( self.spec.opcode_res_status, 11823) self.stop_simulation() self.simulate(test)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,942
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_uart_rx.py
from myhdl import (Signal, ResetSignal, intbv, Simulation, StopSimulation, instance, delay, now) from unittest import TestCase from fpgaedu.hdl import ClockGen, UartRx from random import randint class UartRxTestCase(TestCase): DATA_BITS = 8 STOP_BITS = 1 HALF_PERIOD = 5 RX_DIV = 4 HIGH = True LOW = False START = LOW STOP = HIGH IDLE = HIGH def setUp(self): self.clk = Signal(True) self.reset = ResetSignal(True, active=False, async=False) self.rx = Signal(False) self.rx_data = Signal(intbv(0)[self.DATA_BITS:0]) self.rx_finish = Signal(False) self.rx_busy = Signal(False) self.rx_baud_tick = Signal(False) self.clockgen = ClockGen(self.clk, self.HALF_PERIOD) self.uart_rx = UartRx(self.clk, self.reset, self.rx, self.rx_data, self.rx_finish, self.rx_busy, self.rx_baud_tick, data_bits=self.DATA_BITS, stop_bits=self.STOP_BITS, rx_div=self.RX_DIV) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.uart_rx, *test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_rx_receive(self): test_data = ['10101010', '00110011', '011001110'] @instance def monitor(): for data in test_data: yield self.rx_finish.posedge self.assertEquals(self.rx_data, int(data, 2)) @instance def test(): self.rx.next = self.IDLE self.rx_baud_tick.next = False self.reset.next = False yield self.clk.negedge self.reset.next = True yield self.clk.negedge def baud_tick(n): for _ in range(n): for _ in range(49): yield self.clk.negedge self.rx_baud_tick.next = True yield self.clk.negedge self.rx_baud_tick.next = False yield self.clk.negedge for data in test_data: self.rx.next = self.START yield baud_tick(self.RX_DIV) for bit in data[::-1]: self.rx.next = (bit == '1') yield baud_tick(self.RX_DIV) self.rx.next = self.STOP yield baud_tick(self.RX_DIV) yield baud_tick(self.RX_DIV) self.stop_simulation() self.simulate([test, monitor])
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,943
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/_controllerspec.py
from math import ceil from myhdl import intbv class ControllerSpec(): ''' address-type message layout - width_opcode: 8 - width_addr: 32 - width_data: 8 47 40 39 \ \ 8 7 0 |----opcode---| |----address---/ /----| |-----data----| | | | \ \ | | | |-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-/ /-|-|-|-|-|-|-|-|-|-|-| \ \ value-type message layout - width_opcode: 8 - width_addr: 40 47 40 39 \ \ 0 |----opcode---| |----value-------------------/ /------| | | | \ \ | |-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-/ /-|-|-|-| \ \ ''' _WIDTH_BYTE = 8 # opcode width = 4 => 2^4=16 opcodes possible _WIDTH_OPCODE = 4 _OPCODE_CMD_READ = 0 # - addr _OPCODE_CMD_WRITE = 1 # - addr # - data _OPCODE_CMD_RESET = 2 _OPCODE_CMD_STEP = 3 _OPCODE_CMD_START = 4 _OPCODE_CMD_PAUSE = 5 _OPCODE_CMD_STATUS = 6 _OPCODE_RES_READ_SUCCESS = 0 # - addr # - data _OPCODE_RES_READ_ERROR_MODE = 1 # - addr _OPCODE_RES_WRITE_SUCCESS = 2 # - addr # - data _OPCODE_RES_WRITE_ERROR_MODE = 3 # - addr # - data _OPCODE_RES_RESET_SUCCESS = 4 _OPCODE_RES_STEP_SUCCESS = 5 # - value (cycle count after step) _OPCODE_RES_STEP_ERROR_MODE = 6 _OPCODE_RES_START_SUCCESS = 7 # - value (cycle count before start) _OPCODE_RES_START_ERROR_MODE = 8 _OPCODE_RES_PAUSE_SUCCESS = 9 # - value (cycle count after pause) _OPCODE_RES_PAUSE_ERROR_MODE = 10 _OPCODE_RES_STATUS = 11 # - value (mode + cycle count) _ADDR_TYPE_CMD_OPCODES = [_OPCODE_CMD_READ, _OPCODE_CMD_WRITE] _ADDR_TYPE_RES_OPCODES = [_OPCODE_RES_READ_SUCCESS, _OPCODE_RES_READ_ERROR_MODE, _OPCODE_RES_WRITE_SUCCESS, _OPCODE_RES_WRITE_ERROR_MODE] _CHR_START = 0x12 _CHR_STOP = 0x13 _CHR_ESC = 0x7D def __init__(self, width_addr, width_data): if width_addr < 1: raise ValueError('address width must be at least 1') if width_data < 1: raise ValueError('data width must be at least 1') self._width_addr = width_addr self._width_data = width_data @property def width_opcode(self): return self._WIDTH_OPCODE @property def width_addr(self): return self._width_addr @property def width_data(self): return self._width_data @property def width_value(self): return self.width_addr + self.width_data @property def width_message(self): return self.width_opcode + self.width_value @property def width_message_bytes(self): return int(ceil(float(self.width_message) / float(self._WIDTH_BYTE))) @property def index_opcode_high(self): return self.width_message - 1 @property def index_opcode_low(self): return self.width_message - self.width_opcode @property def index_addr_high(self): return self.width_message - self.width_opcode - 1 @property def index_addr_low(self): return self.width_message - self.width_opcode - self.width_addr @property def index_data_high(self): return self.width_data - 1 @property def index_data_low(self): return 0 @property def index_value_high(self): return self.width_value - 1 @property def index_value_low(self): return 0 #Command opcodes @property def opcode_cmd_read(self): return self._OPCODE_CMD_READ @property def opcode_cmd_write(self): return self._OPCODE_CMD_WRITE @property def opcode_cmd_reset(self): return self._OPCODE_CMD_RESET @property def opcode_cmd_step(self): return self._OPCODE_CMD_STEP @property def opcode_cmd_start(self): return self._OPCODE_CMD_START @property def opcode_cmd_pause(self): return self._OPCODE_CMD_PAUSE @property def opcode_cmd_status(self): return self._OPCODE_CMD_STATUS # Repsonse opcodes @property def opcode_res_read_success(self): return self._OPCODE_RES_READ_SUCCESS @property def opcode_res_read_error_mode(self): return self._OPCODE_RES_READ_ERROR_MODE @property def opcode_res_write_success(self): return self._OPCODE_RES_WRITE_SUCCESS @property def opcode_res_write_error_mode(self): return self._OPCODE_RES_WRITE_ERROR_MODE @property def opcode_res_reset_success(self): return self._OPCODE_RES_RESET_SUCCESS @property def opcode_res_step_success(self): return self._OPCODE_RES_STEP_SUCCESS @property def opcode_res_step_error_mode(self): return self._OPCODE_RES_STEP_ERROR_MODE @property def opcode_res_start_success(self): return self._OPCODE_RES_START_SUCCESS @property def opcode_res_start_error_mode(self): return self._OPCODE_RES_START_ERROR_MODE @property def opcode_res_pause_success(self): return self._OPCODE_RES_PAUSE_SUCCESS @property def opcode_res_pause_error_mode(self): return self._OPCODE_RES_PAUSE_ERROR_MODE @property def opcode_res_status(self): return self._OPCODE_RES_STATUS def is_addr_type_command(self, opcode): return (opcode in self._ADDR_TYPE_CMD_OPCODES) def is_value_type_command(self, opcode): return not self.is_addr_type_command(opcode) def is_addr_type_response(self, opcode): return (opcode in self._ADDR_TYPE_RES_OPCODES) def is_value_type_response(self, opcode): return not self.is_addr_type_response(opcode) def value_type_message(self, opcode, value): message = intbv(0)[self.width_message:0] message[self.index_opcode_high+1:self.index_opcode_low] = opcode message[self.index_value_high+1:self.index_value_low] = value return int(message) def addr_type_message(self, opcode, address, data): message = intbv(0)[self.width_message:0] message[self.index_opcode_high+1:self.index_opcode_low] = opcode message[self.index_addr_high+1:self.index_addr_low] = address message[self.index_data_high+1:self.index_data_low] = data return int(message) def parse_opcode(self, message): m = intbv(message) return int(m[self.index_opcode_high+1:self.index_opcode_low]) def parse_addr(self, message): m = intbv(message) return int(m[self.index_addr_high+1:self.index_addr_low]) def parse_data(self, message): m = intbv(message) return int(m[self.index_data_high+1:self.index_data_low]) def parse_value(self, message): m = intbv(message) return int(m[self.index_value_high+1:self.index_value_low]) @property def chr_start(self): return self._CHR_START @property def chr_stop(self): return self._CHR_STOP @property def chr_esc(self): return self._CHR_ESC
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,944
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_controller_control.py
from myhdl import (always_comb, Signal) def ControllerControl(spec, reset, opcode_cmd, opcode_res, rx_ready, cycle_autonomous, rx_next, tx_ready, nop, exp_wen, exp_reset, cycle_start, cycle_pause, cycle_step, exp_reset_active=False): ''' Input signals: opcode_cmd rx_ready cycle_autonomous tx_ready Output signals: opcode_res rx_next nop exp_wen exp_reset cycle_start cycle_pause cycle_step ''' nop_int = Signal(True) @always_comb def internal_logic(): nop_int.next = (not rx_ready or not tx_ready or reset == reset.active) @always_comb def output_logic(): rx_next.next = not nop_int nop.next = nop_int exp_wen.next = (opcode_cmd == spec.opcode_cmd_write and not cycle_autonomous and not nop_int and reset != reset.active) if ((reset == reset.active) or (opcode_cmd == spec.opcode_cmd_reset and not nop_int)): exp_reset.next = exp_reset_active else: exp_reset.next = not exp_reset_active # Set opcode_res opcode_res.next = 0 if reset == reset.active: opcode_res.next = 0 if opcode_cmd == spec.opcode_cmd_read and not cycle_autonomous: opcode_res.next = spec.opcode_res_read_success elif opcode_cmd == spec.opcode_cmd_read and cycle_autonomous: opcode_res.next = spec.opcode_res_read_error_mode elif opcode_cmd == spec.opcode_cmd_write and not cycle_autonomous: opcode_res.next = spec.opcode_res_write_success elif opcode_cmd == spec.opcode_cmd_write and cycle_autonomous: opcode_res.next = spec.opcode_res_write_error_mode elif opcode_cmd == spec.opcode_cmd_reset: opcode_res.next = spec.opcode_res_reset_success elif opcode_cmd == spec.opcode_cmd_step and not cycle_autonomous: opcode_res.next = spec.opcode_res_step_success elif opcode_cmd == spec.opcode_cmd_step and cycle_autonomous: opcode_res.next = spec.opcode_res_step_error_mode elif opcode_cmd == spec.opcode_cmd_start and not cycle_autonomous: opcode_res.next = spec.opcode_res_start_success elif opcode_cmd == spec.opcode_cmd_start and cycle_autonomous: opcode_res.next = spec.opcode_res_start_error_mode elif opcode_cmd == spec.opcode_cmd_pause and cycle_autonomous: opcode_res.next = spec.opcode_res_pause_success elif opcode_cmd == spec.opcode_cmd_pause and not cycle_autonomous: opcode_res.next = spec.opcode_res_pause_error_mode elif opcode_cmd == spec.opcode_cmd_status: opcode_res.next = spec.opcode_res_status cycle_start.next = (opcode_cmd == spec.opcode_cmd_start and not cycle_autonomous and not nop_int and reset != reset.active) cycle_pause.next = (opcode_cmd == spec.opcode_cmd_pause and cycle_autonomous and not nop_int and reset != reset.active) cycle_step.next = (opcode_cmd == spec.opcode_cmd_step and not cycle_autonomous and not nop_int and reset != reset.active) return internal_logic, output_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,945
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/nexys4/test_board_component_rx.py
from unittest import TestCase from myhdl import (Signal, intbv, ResetSignal, instance, delay, Simulation, StopSimulation, now, bin) from fpgaedu import ControllerSpec from fpgaedu.hdl import ClockGen from fpgaedu.hdl.nexys4 import BoardComponentRx class BoardComponentRxTestCase(TestCase): HALF_PERIOD = 5 UART_RX_BAUD_DIV = 8 LVL_HIGH = True LVL_LOW = False LVL_START = LVL_LOW LVL_STOP = LVL_HIGH LVL_IDLE = LVL_HIGH def setUp(self): self.spec = ControllerSpec(width_addr=32, width_data=8) # Input signals self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.rx = Signal(False) self.rx_next = Signal(False) self.uart_rx_baud_tick = Signal(False) # Output signals self.rx_msg = Signal(intbv(0)[self.spec.width_message:0]) self.rx_ready = Signal(False) self.clockgen = ClockGen(clk=self.clk, half_period=self.HALF_PERIOD) self.component_rx = BoardComponentRx(spec=self.spec, clk=self.clk, reset=self.reset, rx=self.rx, rx_msg=self.rx_msg, rx_ready=self.rx_ready, rx_next=self.rx_next, uart_rx_baud_tick=self.uart_rx_baud_tick, uart_rx_baud_div=self.UART_RX_BAUD_DIV) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.component_rx, *test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_rx(self): @instance def monitor(): yield self.rx_ready.posedge, delay(500000) yield delay(1) print(now()) self.assertEquals(self.rx_msg, 0x0FFFFFFFFFFF) self.assertTrue(self.rx_ready) self.stop_simulation() @instance def stimulant(): yield self.clk.negedge self.rx.next = self.LVL_IDLE self.reset.next = not self.reset.active self.rx_next.next = False self.uart_rx_baud_tick.next = False yield self.clk.negedge def baud_ticks(n_ticks): for _ in range(n_ticks): for _ in range(5): yield self.clk.negedge self.uart_rx_baud_tick.next = True yield self.clk.negedge self.uart_rx_baud_tick.next = False yield self.clk.negedge def transmit(char): yield baud_ticks(self.UART_RX_BAUD_DIV) self.rx.next = self.LVL_START yield baud_ticks(self.UART_RX_BAUD_DIV) indexes = range(8)[::-1] for i in indexes: lvl = bin(char, width=8)[i] == '1' self.rx.next = lvl yield baud_ticks(self.UART_RX_BAUD_DIV) self.rx.next = self.LVL_STOP yield baud_ticks(self.UART_RX_BAUD_DIV) yield transmit(0x1) yield transmit(self.spec.chr_start) for i in range(8): yield transmit(0xFF) yield transmit(self.spec.chr_stop) # for i in range(8): # self.rx.next = self.LVL_START # for i in range(8): # yield self.clk.negedge # # self.rx.next = self.LVL_HIGH # for i in range(8*8): # yield self.clk.negedge # # self.rx.next = self.LVL_STOP # for i in range(8): # yield self.clk.negedge self.simulate([monitor, stimulant])
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,946
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_fifo.py
from myhdl import (Signal, ResetSignal, intbv, Simulation, StopSimulation, instance, delay, now, traceSignals) from math import ceil import unittest from unittest import TestCase from random import randint from fpgaedu.hdl import Fifo, ClockGen class FifoTestCase(TestCase): CLK_HALF_PERIOD = 5 DATA_WIDTH = 32 DEPTH = 2 def setUp(self): self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.din = Signal(intbv(0)[self.DATA_WIDTH:0]) self.enqueue = Signal(False) self.dout = Signal(intbv(0)[self.DATA_WIDTH:0]) self.dequeue = Signal(False) self.empty = Signal(False) self.full = Signal(False) self.clockgen = ClockGen(self.clk, self.CLK_HALF_PERIOD) self.fifo = Fifo(self.clk, self.reset, self.din, self.enqueue, self.dout, self.dequeue, self.empty, self.full, data_width=self.DATA_WIDTH, depth=self.DEPTH) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.fifo, test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_fifo(self): @instance def test(): self.reset.next = False yield self.clk.negedge self.reset.next = True yield self.clk.negedge self.assertEquals(self.dout, 0) self.assertTrue(self.empty) self.assertFalse(self.full) self.din.next = 34 self.enqueue.next = True yield self.clk.negedge self.assertEquals(self.dout, 34) self.assertFalse(self.empty) self.assertFalse(self.full) self.enqueue.next = False for i in range(40): yield self.clk.negedge self.din.next = 23 self.enqueue.next = True yield self.clk.negedge self.assertEquals(self.dout, 34) self.assertFalse(self.empty) self.assertTrue(self.full) self.enqueue.next = False self.assertEquals(self.dout, 34) yield self.clk.negedge self.dequeue.next = True yield self.clk.negedge self.dequeue.next = False self.assertEquals(self.dout, 23) self.assertFalse(self.empty) self.assertFalse(self.full) self.dequeue.next = True yield self.clk.negedge self.assertEquals(self.dout, 0) self.assertTrue(self.empty) self.assertFalse(self.full) self.dequeue.next = False yield self.clk.negedge self.assertEquals(self.dout, 0) self.assertTrue(self.empty) self.assertFalse(self.full) self.stop_simulation() self.simulate(test)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,947
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/__init__.py
from ._clockgen import ClockGen from ._rom import Rom from ._ram import Ram from ._uart_tx import UartTx from ._uart_rx import UartRx from ._baudgen import BaudGen from ._baudgen_rx_lookup import BaudGenRxLookup from ._controller import Controller from ._fifo import Fifo from ._message_receiver import MessageReceiver from ._message_transmitter import MessageTransmitter from ._test_experiment import TestExperiment
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,948
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_controller.py
from myhdl import always, always_seq, always_comb, enum, Signal, intbv from fpgaedu import ControllerSpec from fpgaedu.hdl._controller_control import ControllerControl from fpgaedu.hdl._controller_cycle_control import ControllerCycleControl from fpgaedu.hdl._controller_response_compose import ControllerResponseCompose def Controller(spec, clk, reset, rx_msg, rx_next, rx_ready, tx_msg, tx_next, tx_ready, exp_addr, exp_data_write, exp_data_read, exp_wen, exp_reset, exp_clk_en, exp_reset_active=False): ''' spec the controller specification clk Clock input reset Reset input rx_* rx_signals tx_* tx signals exp_addr Output signal setting the address for the experiment to be operated on exp_data_write Output signal setting the value to write to the experiment exp_data_read Input signal containing the data that is read from the experiment exp_wen Output pulse signal indicating to the experiment that the current operation is a write operation exp_reset Output signal indicating to the experiment that it is to be reset to its initial state exp_clk_en Output clock enable signal for the experiment ''' # Pipeline registers ex_res_opcode_res_reg = Signal(intbv(0)[spec.width_opcode:0]) ex_res_opcode_res_next = Signal(intbv(0)[spec.width_opcode:0]) ex_res_nop_reg = Signal(True) ex_res_nop_next = Signal(True) ex_res_cycle_count_reg = Signal(intbv(0)[spec.width_value:0]) ex_res_cycle_count_next = Signal(intbv(0)[spec.width_value:0]) ex_res_addr_reg = Signal(intbv(0)[spec.width_addr:0]) ex_res_addr_next = Signal(intbv(0)[spec.width_addr:0]) #internal signals cycle_autonomous = Signal(False) cycle_start = Signal(False) cycle_pause = Signal(False) cycle_step = Signal(False) cmd_message = rx_msg cmd_opcode = Signal(intbv(0)[spec.width_opcode:0]) cmd_addr = Signal(intbv(0)[spec.width_addr:0]) cmd_data = Signal(intbv(0)[spec.width_data:0]) # EX stage instances control = ControllerControl(spec=spec, opcode_cmd=cmd_opcode, reset=reset, opcode_res=ex_res_opcode_res_next, rx_ready=rx_ready, cycle_autonomous=cycle_autonomous, rx_next=rx_next, tx_ready=tx_ready, nop=ex_res_nop_next, exp_wen=exp_wen, exp_reset=exp_reset, cycle_start=cycle_start, cycle_pause=cycle_pause, cycle_step=cycle_step, exp_reset_active=exp_reset_active) cycle_control = ControllerCycleControl(spec=spec, clk=clk, reset=reset, start=cycle_start, pause=cycle_pause, step=cycle_step, cycle_autonomous=cycle_autonomous, cycle_count=ex_res_cycle_count_next, exp_clk_en=exp_clk_en) # RES stage instances res_compose = ControllerResponseCompose(spec=spec, opcode_res=ex_res_opcode_res_reg, addr=ex_res_addr_reg, data=exp_data_read, nop=ex_res_nop_reg, cycle_count=ex_res_cycle_count_reg, tx_ready=tx_ready, tx_next=tx_next, tx_msg=tx_msg) @always_seq(clk.posedge, reset) def pipeline_register_logic(): ex_res_opcode_res_reg.next = ex_res_opcode_res_next ex_res_nop_reg.next = ex_res_nop_next ex_res_cycle_count_reg.next = ex_res_cycle_count_next ex_res_addr_reg.next = ex_res_addr_next @always_comb def pipeline_next_state_logic(): ex_res_addr_next.next = cmd_addr @always_comb def experiment_setup_connections(): exp_addr.next = cmd_addr exp_data_write.next = cmd_data @always_comb def split_cmd(): cmd_opcode.next = cmd_message[spec.index_opcode_high+1: spec.index_opcode_low] cmd_addr.next = cmd_message[spec.index_addr_high+1: spec.index_addr_low] cmd_data.next = cmd_message[spec.index_data_high+1: spec.index_data_low] return (control, cycle_control, res_compose, split_cmd, experiment_setup_connections, pipeline_register_logic, pipeline_next_state_logic)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,949
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/_board_component_rx.py
from myhdl import Signal, intbv from fpgaedu.hdl import UartRx, Fifo, MessageReceiver def BoardComponentRx(spec, clk, reset, rx, rx_msg, rx_ready, rx_next, uart_rx_baud_tick, uart_rx_baud_div=8): ''' clk Clock input reset Reset input rx rx input rx_msg Output which exposes the received message rx_ready Output indicating that a message has been received successfully, and is ready to be read the message is output on recv_data rx_next Input signalling the component to start receiving the next message ''' uart_rx_data = Signal(intbv(0)[8:0]) uart_rx_finish = Signal(False) uart_rx_busy = Signal(False) fifo_rx_dout = Signal(intbv(0)[8:0]) fifo_rx_dequeue = Signal(False) fifo_rx_empty = Signal(False) fifo_rx_full = Signal(False) uart_rx = UartRx(clk=clk, reset=reset, rx=rx, rx_data=uart_rx_data, rx_finish=uart_rx_finish, rx_busy=uart_rx_busy, rx_baud_tick=uart_rx_baud_tick, data_bits=8, stop_bits=1, rx_div=uart_rx_baud_div) fifo_rx = Fifo(clk=clk, reset=reset, din=uart_rx_data, dout=fifo_rx_dout, enqueue=uart_rx_finish, dequeue=fifo_rx_dequeue, empty=fifo_rx_empty, full=fifo_rx_full, data_width=8, depth=12) receiver = MessageReceiver(spec=spec, clk=clk, reset=reset, rx_fifo_data_read=fifo_rx_dout, rx_fifo_empty=fifo_rx_empty, rx_fifo_dequeue=fifo_rx_dequeue, message=rx_msg, message_ready=rx_ready, receive_next=rx_next) return uart_rx, fifo_rx, receiver
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,950
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/core/test_controllerspec.py
from unittest import TestCase from fpgaedu import ControllerSpec class ControllerSpecTestCase(TestCase): def setUp(self): pass def test_constructor(self): with self.assertRaises(ValueError): spec = ControllerSpec(0, 1) with self.assertRaises(ValueError): spec = ControllerSpec(1, 0) def test_width_and_index_attrs(self): width_data = 12 width_addr = 22 width_opcode = 4 width_value = 34 width_message = 38 width_message_bytes = 5 spec = ControllerSpec(width_addr, width_data) self.assertEquals(spec.width_opcode, width_opcode, '_WIDTH_OPCODE constant has changed') self.assertEquals(spec.width_data, width_data) self.assertEquals(spec.width_addr, width_addr) self.assertEquals(spec.width_value,width_value) self.assertEquals(spec.width_message, width_message) self.assertEquals(spec.width_message_bytes, width_message_bytes) self.assertEquals(spec.index_opcode_high, 37) self.assertEquals(spec.index_opcode_low, 34) self.assertEquals(spec.index_addr_high, 33) self.assertEquals(spec.index_addr_low, 12) self.assertEquals(spec.index_data_high, 11) self.assertEquals(spec.index_data_low, 0) self.assertEquals(spec.index_value_high, 33) self.assertEquals(spec.index_value_low, 0) def test_cmd_opcodes_defined(self): spec = ControllerSpec(1,1) self.assertIsInstance(spec.opcode_cmd_read, int) self.assertIsInstance(spec.opcode_cmd_write, int) self.assertIsInstance(spec.opcode_cmd_reset, int) self.assertIsInstance(spec.opcode_cmd_step, int) self.assertIsInstance(spec.opcode_cmd_start, int) self.assertIsInstance(spec.opcode_cmd_pause, int) self.assertIsInstance(spec.opcode_cmd_status, int) def test_cmd_opcodes_unique(self): spec = ControllerSpec(1,1) cmd_opcodes = [spec.opcode_cmd_read, spec.opcode_cmd_write, spec.opcode_cmd_reset, spec.opcode_cmd_step, spec.opcode_cmd_start, spec.opcode_cmd_pause, spec.opcode_cmd_status] self.assertEquals(len(set(cmd_opcodes)), len(cmd_opcodes)) def test_res_opcodes_defined(self): spec = ControllerSpec(1,1) self.assertIsInstance(spec.opcode_res_read_success, int) self.assertIsInstance(spec.opcode_res_read_error_mode, int) self.assertIsInstance(spec.opcode_res_write_success, int) self.assertIsInstance(spec.opcode_res_write_error_mode, int) self.assertIsInstance(spec.opcode_res_reset_success, int) self.assertIsInstance(spec.opcode_res_step_success, int) self.assertIsInstance(spec.opcode_res_step_error_mode, int) self.assertIsInstance(spec.opcode_res_start_success, int) self.assertIsInstance(spec.opcode_res_start_error_mode, int) self.assertIsInstance(spec.opcode_res_pause_success, int) self.assertIsInstance(spec.opcode_res_pause_error_mode, int) self.assertIsInstance(spec.opcode_res_status, int) def test_res_opcodes_unique(self): spec = ControllerSpec(1,1) res_opcodes = [spec.opcode_res_read_success, spec.opcode_res_read_error_mode, spec.opcode_res_write_success, spec.opcode_res_write_error_mode, spec.opcode_res_reset_success, spec.opcode_res_step_success, spec.opcode_res_step_error_mode, spec.opcode_res_start_success, spec.opcode_res_start_error_mode, spec.opcode_res_pause_success, spec.opcode_res_pause_error_mode, spec.opcode_res_status] self.assertEquals(len(set(res_opcodes)), len(res_opcodes)) def test_message_classification(self): spec = ControllerSpec(1,1) # Test one from within the set self.assertTrue(spec.is_addr_type_response( spec.opcode_res_read_success)) self.assertFalse(spec.is_value_type_response( spec.opcode_res_read_success)) # Test one from outside the set self.assertFalse(spec.is_addr_type_command( spec.opcode_cmd_step)) self.assertTrue(spec.is_value_type_command( spec.opcode_cmd_step)) def test_value_type_message(self): spec = ControllerSpec(8, 8) opcode = int('1010', 2) value = int('1100110011001100', 2) expected = int('10101100110011001100', 2) message = spec.value_type_message(opcode, value) self.assertEquals(message, expected) with self.assertRaises(ValueError): value = int('11111111111111111', 2) message = spec.value_type_message(opcode, value) def test_addr_type_message(self): spec = ControllerSpec(8, 8) opcode = int('1010', 2) address = int('10111111', 2) data = int('11111111', 2) expected = int('10101011111111111111', 2) message = spec.addr_type_message(opcode, address, data) self.assertEquals(message, expected) with self.assertRaises(ValueError): data = int('111111111', 2) message = spec.addr_type_message(opcode, address, data) def test_parse(self): spec = ControllerSpec(8, 8) message = int('10101100110011110000', 2) parsed_opcode = spec.parse_opcode(message) self.assertEquals(parsed_opcode, int('1010', 2)) parsed_addr = spec.parse_addr(message) self.assertEquals(parsed_addr, int('11001100', 2)) parsed_data = spec.parse_data(message) self.assertEquals(parsed_data, int('11110000', 2)) parsed_value = spec.parse_value(message) self.assertEquals(parsed_value, int('1100110011110000', 2)) def test_chr_start(self): spec = ControllerSpec(8, 8) self.assertEquals(spec.chr_start, 0x12) def test_chr_stop(self): spec = ControllerSpec(8, 8) self.assertEquals(spec.chr_stop, 0x13) def test_chr_esc(self): spec = ControllerSpec(8, 8) self.assertEquals(spec.chr_esc, 0x7D)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,951
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_baudgen_rx_lookup.py
from myhdl import * def BaudGenRxLookup(dout, addr): CONTENT = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16) @always_comb def read(): dout.next = CONTENT[int(addr)] return read
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,952
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/nexys4/_board_component_tx.py
from myhdl import Signal, intbv, always_comb from fpgaedu.hdl import UartTx, Fifo, MessageTransmitter def BoardComponentTx(spec, clk, reset, tx, tx_msg, tx_ready, tx_next, uart_tx_baud_tick): ''' clk Clock input reset Reset input tx uart tx output tx_msg Input on which the output message data can be set tx_ready Output indicating that the component is ready to transmit the next message tx_next Input signal instructing the component to transmit the message as set on tx_msg ''' uart_tx_data = Signal(intbv(0)[8:0]) uart_tx_start = Signal(False) uart_tx_busy = Signal(False) fifo_tx_din = Signal(intbv(0)[8:0]) fifo_tx_enqueue = Signal(False) fifo_tx_dout = Signal(intbv(0)[8:0]) fifo_tx_dequeue = Signal(False) fifo_tx_empty = Signal(False) fifo_tx_full = Signal(False) uart_tx = UartTx(clk=clk, reset=reset, tx=tx, tx_data=uart_tx_data, tx_start=uart_tx_start, tx_busy=uart_tx_busy, baud_tick=uart_tx_baud_tick, data_bits=8, stop_bits=1) #fifo_tx = Fifo(clk=clk, reset=reset, din=fifo_tx_din, # enqueue=fifo_tx_enqueue, dout=fifo_tx_dout, # dequeue=fifo_tx_dequeue, empty=fifo_tx_empty, full=fifo_tx_full, # data_width=8, depth=12) #transmitter = MessageTransmitter(spec=spec, clk=clk, reset=reset, # tx_fifo_data_write=fifo_tx_din, tx_fifo_full=fifo_tx_full, # tx_fifo_enqueue=fifo_tx_enqueue, message=tx_msg, # ready=tx_ready, transmit_next=tx_next) transmitter = MessageTransmitter(spec=spec, clk=clk, reset=reset, tx_fifo_data_write=uart_tx_data, tx_fifo_full=uart_tx_busy, tx_fifo_enqueue=uart_tx_start, message=tx_msg, ready=tx_ready, transmit_next=tx_next) #@always_comb #def fifo_to_uart_logic(): # uart_tx_data.next = fifo_tx_dout # uart_tx_start.next = (not uart_tx_busy and not fifo_tx_empty) # fifo_tx_dequeue.next = (not uart_tx_busy and not fifo_tx_empty) #return uart_tx, fifo_tx, transmitter, fifo_to_uart_logic return uart_tx, transmitter
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,953
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/fpgaedu/hdl/_uart_tx.py
from myhdl import * def UartTx(clk, reset, tx, tx_data, tx_start, tx_busy, baud_tick, data_bits=8, stop_bits=1): """ clk input Clock signal reset input Reset signal tx output Tx line tx_data input data to transmit tx_start input tx_busy output baud_tick input """ state_t = enum('READY', 'WAIT_START', 'SEND_START', 'SEND_DATA', 'SEND_STOP') state_reg = Signal(state_t.READY) state_next = Signal(state_t.READY) data_reg = Signal(intbv(0)[data_bits:0]) data_next = Signal(intbv(0)[data_bits:0]) count_reg = Signal(intbv(0, min=0, max=data_bits)) count_next = Signal(intbv(0, min=0, max=8)) LVL_HIGH = True LVL_LOW = False LVL_START = LVL_LOW LVL_STOP = LVL_HIGH LVL_IDLE = LVL_HIGH @always_seq(clk.posedge, reset=reset) def reg_logic(): state_reg.next = state_next data_reg.next = data_next count_reg.next = count_next @always_comb def next_state_logic(): state_next.next = state_reg data_next.next = data_reg count_next.next = 0 if state_reg == state_t.READY: if tx_start: state_next.next = state_t.WAIT_START data_next.next = tx_data elif tx_start and baud_tick: state_next.next = state_t.SEND_START data_next.next = tx_data elif state_reg == state_t.WAIT_START: if baud_tick: state_next.next = state_t.SEND_START elif state_reg == state_t.SEND_START: if baud_tick: state_next.next = state_t.SEND_DATA elif state_reg == state_t.SEND_DATA: if baud_tick: count_next.next = (count_reg + 1) % data_bits if count_reg == data_bits - 1: state_next.next = state_t.SEND_STOP else: count_next.next = count_reg elif state_reg == state_t.SEND_STOP: if baud_tick: count_next.next = (count_reg + 1) % stop_bits state_next.next = state_t.READY @always_comb def output_logic(): tx.next = LVL_IDLE tx_busy.next = True if state_reg == state_t.READY: tx_busy.next = False elif state_reg == state_t.WAIT_START: pass elif state_reg == state_t.SEND_START: tx.next = LVL_START elif state_reg == state_t.SEND_DATA: tx.next = data_reg[count_reg] elif state_reg == state_t.SEND_STOP: tx.next = LVL_STOP return reg_logic, next_state_logic, output_logic
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,954
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_uart_tx.py
from myhdl import (Signal, ResetSignal, intbv, Simulation, StopSimulation, instance, delay) from math import ceil from unittest import TestCase from random import randint from fpgaedu.hdl import ClockGen, UartTx class UartTxTestCase(TestCase): DATA_BITS = 8 STOP_BITS = 1 HALF_PERIOD = 10 HIGH = True LOW = False START = LOW STOP = HIGH IDLE = HIGH def setUp(self): self.clk = Signal(False) self.reset = ResetSignal(True,active=False,async=True) self.tx = Signal(False) self.tx_start = Signal(False) self.tx_busy = Signal(False) self.tx_data = Signal(intbv(0)[self.DATA_BITS:0]) self.baud_tick = Signal(False) self.clockgen = ClockGen(self.clk, self.HALF_PERIOD) self.uart_tx = UartTx(self.clk, self.reset, self.tx, self.tx_data, self.tx_start, self.tx_busy, self.baud_tick) def tearDown(self): del self.clk del self.reset del self.tx del self.tx_start del self.tx_busy del self.tx_data del self.baud_tick del self.clockgen del self.uart_tx def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.uart_tx, test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_initial_state(self): @instance def test(): yield delay(1) self.assertEquals(self.tx, True) self.assertEquals(self.tx_busy, False) self.stop_simulation() self.simulate(test) def test_idle_behaviour(self): @instance def test(): yield self.clk.negedge self.assertEquals(self.tx, bool(self.IDLE)) yield self.clk.negedge self.assertEquals(self.tx, bool(self.IDLE)) self.stop_simulation() self.simulate(test) def test_transmit(self): @instance def test(): yield self.clk.negedge #test_data = ['01001010'] test_data = ['01001010', '11001111', '11110111'] for test_data_str in test_data: print(test_data_str) #check that uart is ready self.assertFalse(self.tx_busy) self.assertEquals(self.tx, self.IDLE) self.tx_data.next = int(test_data_str, 2) self.tx_start.next = True yield self.clk.negedge self.assertTrue(self.tx_busy) self.assertEquals(self.tx, self.IDLE) yield self.clk.negedge self.tx_start.next = False self.assertEquals(self.tx, self.IDLE) self.baud_tick.next = True yield self.clk.negedge self.baud_tick.next = False self.assertEquals(self.tx, self.START) # test that the tx signal remains stable over a random # number of cycles when baud_tick is low for _ in range(randint(20,100)): yield self.clk.negedge self.assertEquals(self.tx, self.START) #Test data transmission for test_data_chr in test_data_str[::-1]: self.baud_tick.next = True yield self.clk.negedge self.baud_tick.next = False def strtolvl(s): if s == '0': return self.LOW elif s == '1': return self.HIGH self.assertEquals(self.tx, strtolvl(test_data_chr)) # test that the tx signal remains stable over a random # number of cycles when baud_tick is low for _ in range(randint(20,100)): yield self.clk.negedge self.assertEquals(self.tx, strtolvl(test_data_chr)) self.baud_tick.next = True yield self.clk.negedge self.baud_tick.next = False self.assertEquals(self.tx, self.STOP) # test that the tx signal remains stable over a random # number of cycles when baud_tick is low for _ in range(randint(20,100)): yield self.clk.negedge self.assertEquals(self.tx, self.STOP) self.assertTrue(self.tx_busy) self.baud_tick.next = True yield self.clk.negedge self.assertEquals(self.tx, self.IDLE) self.baud_tick.next = False yield self.clk.negedge self.assertFalse(self.tx_busy) self.assertEquals(self.tx, self.IDLE) self.stop_simulation() self.simulate(test)
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,955
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/test_clockgen.py
import unittest from unittest import TestCase from myhdl import (Signal, Simulation, delay, instance, now, StopSimulation, traceSignals) from fpgaedu.hdl import ClockGen class ClockGenTestCase(TestCase): def test_clockgen_basic(self): clk = Signal(False) half_period = 10 clockgen = ClockGen(clk, half_period) @instance def test(): for i in range(0, 100, 2): self.assertEquals(now(), i*half_period) yield clk.posedge self.assertEquals(now(), (i+1)*half_period) yield clk.negedge raise StopSimulation() sim = Simulation(clockgen, test) sim.run() if __name__ == '__main__': unittest.main()
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,956
matthijsbos/fpgaedu-nexys4-python
refs/heads/master
/tests/hdl/nexys4/test_board_component_tx.py
from myhdl import (Signal, intbv, ResetSignal, instance, Simulation, StopSimulation, delay) from unittest import TestCase from fpgaedu import ControllerSpec from fpgaedu.hdl import ClockGen from fpgaedu.hdl.nexys4 import BoardComponentTx class BoardComponentTxTestCase(TestCase): HALF_PERIOD = 5 LVL_HIGH = True LVL_LOW = False LVL_START = LVL_LOW LVL_STOP = LVL_HIGH LVL_IDLE = LVL_HIGH def setUp(self): self.spec = ControllerSpec(width_addr=32, width_data=8) # Input signals self.clk = Signal(False) self.reset = ResetSignal(True, active=False, async=False) self.tx_next = Signal(False) self.tx_msg = Signal(intbv(0)[self.spec.width_message:0]) self.uart_tx_baud_tick = Signal(False) # Output signals self.tx_ready = Signal(False) self.tx = Signal(False) self.clockgen = ClockGen(clk=self.clk, half_period=self.HALF_PERIOD) self.component_tx = BoardComponentTx(spec=self.spec, clk=self.clk, reset=self.reset, tx=self.tx, tx_msg=self.tx_msg, tx_ready=self.tx_ready, tx_next=self.tx_next, uart_tx_baud_tick=self.uart_tx_baud_tick) def simulate(self, test_logic, duration=None): sim = Simulation(self.clockgen, self.component_tx, *test_logic) sim.run(duration, quiet=False) def stop_simulation(self): raise StopSimulation() def test_tx(self): @instance def test(): yield self.clk.negedge self.reset.next = self.reset.active yield self.clk.negedge self.reset.next = not self.reset.active yield self.clk.negedge self.assertTrue(self.tx_ready) for i in range(100): self.uart_tx_baud_tick.next = True yield self.clk.negedge self.uart_tx_baud_tick.next = False self.assertEquals(self.tx, self.LVL_IDLE) self.tx_msg.next = 0xFFFFFFFF self.tx_next.next = True yield self.clk.negedge self.assertFalse(self.tx_ready) self.tx_next.next = False self.uart_tx_baud_tick.next = True yield self.tx.negedge for i in range(220): yield self.clk.negedge self.stop_simulation() self.simulate([test])
{"/shell.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/_baudgen.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/__init__.py", "/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py"], "/fpgaedu/hdl/nexys4/_test_setup.py": ["/fpgaedu/hdl/nexys4/__init__.py"], "/fpgaedu/hdl/_fifo.py": ["/fpgaedu/hdl/__init__.py"], "/fpgaedu/__init__.py": ["/fpgaedu/_controllerspec.py"], "/fpgaedu/hdl/nexys4/__init__.py": ["/fpgaedu/hdl/nexys4/_clock_enable_buffer.py", "/fpgaedu/hdl/nexys4/_board_component.py", "/fpgaedu/hdl/nexys4/_board_component_rx.py", "/fpgaedu/hdl/nexys4/_board_component_tx.py"], "/tests/hdl/test_controller_response_compose.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/__init__.py": ["/fpgaedu/hdl/_clockgen.py", "/fpgaedu/hdl/_rom.py", "/fpgaedu/hdl/_ram.py", "/fpgaedu/hdl/_uart_tx.py", "/fpgaedu/hdl/_uart_rx.py", "/fpgaedu/hdl/_baudgen.py", "/fpgaedu/hdl/_baudgen_rx_lookup.py", "/fpgaedu/hdl/_controller.py", "/fpgaedu/hdl/_fifo.py", "/fpgaedu/hdl/_message_receiver.py", "/fpgaedu/hdl/_message_transmitter.py", "/fpgaedu/hdl/_test_experiment.py"], "/fpgaedu/hdl/_controller.py": ["/fpgaedu/__init__.py", "/fpgaedu/hdl/_controller_control.py", "/fpgaedu/hdl/_controller_cycle_control.py", "/fpgaedu/hdl/_controller_response_compose.py"], "/fpgaedu/hdl/nexys4/_board_component_rx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/core/test_controllerspec.py": ["/fpgaedu/__init__.py"], "/fpgaedu/hdl/nexys4/_board_component_tx.py": ["/fpgaedu/hdl/__init__.py"], "/tests/hdl/test_clockgen.py": ["/fpgaedu/hdl/__init__.py"]}
74,959
srwei/ezrecipe
refs/heads/master
/backend/ezrecipe/urls.py
from rest_framework import routers from .api import IngredientsViewSet, RecipesViewset, RecipeIngredientsViewset, InputIngredientsViewset from .views import ReturnRecipeList router = routers.DefaultRouter() router.register('api/ingredients', IngredientsViewSet, 'ingredients') router.register('api/recipes', RecipesViewset, 'recipes') router.register('api/recipeingredients', RecipeIngredientsViewset, 'recipeingredients') router.register('api/inputingredients', InputIngredientsViewset, 'inputingredients') urlpatterns = router.urls
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,960
srwei/ezrecipe
refs/heads/master
/backend/ezrecipe/forms.py
from django import forms from ezrecipe.models import ezrecipe class EnterIngredientsForm(forms.form): ingredients = forms.CharField()
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,961
srwei/ezrecipe
refs/heads/master
/backend/ezrecipe/views.py
from django.shortcuts import render from rest_framework import viewsets # add this from rest_framework.response import Response from rest_framework.views import APIView from .serializers import IngredientsInputSerializer from .models import * from .api import InputIngredientsViewset class ReturnRecipeList(APIView): #def get_queryset(self): # return InputIngredients.objects.all() def post(self, request, format=None): serializer = IngredientsInputSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) ''' def recipe_list(request): if request.method == 'POST': serializer = IngredientsInputSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) '''
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,962
srwei/ezrecipe
refs/heads/master
/backend/ezrecipe/serializers.py
# todo/serializers.py from rest_framework import serializers from ezrecipe.models import Ingredients, Recipes, RecipeIngredients, InputIngredients #Ingredients Serializer class IngredientsSerializer(serializers.ModelSerializer): class Meta: model = Ingredients fields = '__all__' class RecipesSerializer(serializers.ModelSerializer): class Meta: model = Recipes fields = '__all__' class RecipeIngredientsSerializer(serializers.ModelSerializer): class Meta: model = RecipeIngredients fields = '__all__' class IngredientsInputSerializer(serializers.ModelSerializer): class Meta: model = InputIngredients fields = '__all__'
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,963
srwei/ezrecipe
refs/heads/master
/ddl/recipescraper.py
import urllib import re import requests import csv from bs4 import BeautifulSoup from csv import DictReader, DictWriter from socket import error as SocketError from nltk.tokenize import sent_tokenize descriptions = ['baked', 'beaten', 'blanched', 'boiled', 'boiling', 'boned', 'breaded', 'brewed', 'broken', 'chilled', 'chopped', 'cleaned', 'coarse', 'cold', 'cooked', 'cool', 'cooled', 'cored', 'creamed', 'crisp', 'crumbled', 'crushed', 'cubed', 'cut', 'deboned', 'deseeded', 'diced', 'dissolved', 'divided', 'drained', 'dried', 'dry', 'fine', 'firm', 'fluid', 'fresh', 'frozen', 'grated', 'grilled', 'ground', 'halved', 'hard', 'hardened', 'heated', 'heavy', 'juiced', 'julienned', 'jumbo', 'large', 'lean', 'light', 'lukewarm', 'marinated', 'mashed', 'medium', 'melted', 'minced', 'near', 'opened', 'optional', 'packed', 'peeled', 'pitted', 'popped', 'pounded', 'prepared', 'pressed', 'pureed', 'quartered', 'refrigerated', 'rinsed', 'ripe', 'roasted', 'roasted', 'rolled', 'rough', 'scalded', 'scrubbed', 'seasoned', 'seeded', 'segmented', 'separated', 'shredded', 'sifted', 'skinless', 'sliced', 'slight', 'slivered', 'small', 'soaked', 'soft', 'softened', 'split', 'squeezed', 'stemmed', 'stewed', 'stiff', 'strained', 'strong', 'thawed', 'thick', 'thin', 'tied', 'toasted', 'torn', 'trimmed', 'wrapped', 'vained', 'warm', 'washed', 'weak', 'zested', 'wedged', 'skinned', 'gutted', 'browned', 'patted', 'raw', 'flaked', 'deveined', 'shelled', 'shucked', 'crumbs', 'halves', 'squares', 'zest', 'peel', 'uncooked', 'butterflied', 'unwrapped', 'unbaked', 'warmed'] prepositions = ['as', 'such', 'for', 'with', 'without', 'if', 'about', 'e.g.', 'in', 'into', 'at', 'until'] measurement_units = ['teaspoons', 'tablespoons', 'cups', 'containers', 'packets', 'bags', 'quarts', 'pounds', 'cans', 'bottles', 'pints', 'packages', 'ounces', 'jars', 'heads', 'gallons', 'drops', 'envelopes', 'bars', 'boxes', 'pinches', 'dashes', 'bunches', 'recipes', 'layers', 'slices', 'links', 'bulbs', 'stalks', 'squares', 'sprigs', 'fillets', 'pieces', 'legs', 'thighs', 'cubes', 'granules', 'strips', 'trays', 'leaves', 'loaves', 'halves'] unnecessary_words = ['chunks', 'pieces', 'rings', 'spears', 'up', 'purpose'] preceding_words = ['well', 'very', 'super'] succeeding_words = ['diagonally', 'lengthwise', 'overnight'] description_preds = ['removed', 'discarded', 'reserved', 'included', 'inch', 'inches', 'old', 'temperature', 'up'] hyphen_prefixes = ['non', 'reduced', 'semi', 'low'] hyphen_suffixes = ['coated', 'free', 'flavored'] def check_plurals_helper(string, plural_string): if string[0] != plural_string[0]: return None if len(string) > 1 and len(plural_string) > 1 and string[1] != plural_string[1]: return None if len(string) > 2 and len(plural_string) > 2 and string[2] != plural_string[2]: return None if string == plural_string or \ string + 's' == plural_string or \ string + 'es' == plural_string or \ string[:-1] + 'ies' == plural_string or \ string[:-1] + 'ves' == plural_string: return plural_string return None def check_plurals(string, plural_list): for plural_string in plural_list: if check_plurals_helper(string, plural_string[1]): return plural_string if check_plurals_helper(string, plural_string): return plural_string return None # main function def main(): recipe_csv = open('recipes.csv', 'w') recipe_csv.truncate() recipe_csv.close() output_text = open('output.txt', 'w') output_text.truncate() ingredients_csv = open('all_ingredients.csv', 'w') ingredients_csv.truncate() ingredients_csv.close() all_ingredients_csv = open('all_recipe_ingredients.csv', 'w') all_ingredients_csv.truncate() all_ingredients_csv.close() all_ingredients = [] all_recipes = [] all_recipe_ingredients = [] description_regex = re.compile(r"\([^()]*\)") ingredientId_increment = 1 # for recipe_id in range(6660, 27000): for recipe_id in range(7000, 20000): ingredient_count = 0 if recipe_id == 7678: continue print("trying recipe id: {}".format(recipe_id)) soup = None try: url = "http://allrecipes.com/recipe/{}".format(recipe_id) response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") except requests.exceptions.HTTPError as e: output_text.write("{0}: No recipe".format(recipe_id)) # output_text.write(e.response.content) except requests.exceptions.ConnectionError as e: output_text.write("{0}: CONNECTION ERROR".format(recipe_id)) # output_text.write(e.response.content) except SocketError as e: output_text.write("{0}: SOCKET ERROR".format(recipe_id)) # output_text.write(e.response.content) if soup: title_span = soup.find("h1", class_="recipe-summary__h1") serving_span = soup.find("span", class_="servings-count") calorie_span = soup.find("span", class_="calorie-count") direction_span = soup.find_all("span", class_="recipe-directions__list--item") ingredients_object = soup.find_all("span", class_="recipe-ingred_txt") footnotes_span = soup.find_all("section", class_="recipe-footnotes") # get title if not title_span: continue title = title_span.text #all_recipes.append([recipe_id, title]) # get ingredients num_ingredients = len(ingredients_object) - 3 for i in range(num_ingredients): ingredient = {} ingredient_str = ingredients_object[i].text # print(ingredient_str) while True: description = description_regex.search(ingredient_str) if not description: break description_string = description.group() ingredient_str = ingredient_str.replace(description_string, "") ingredient_str = ingredient_str.replace(","," and ") ingredient_str = ingredient_str.replace("-"," ") parsed_ingredient = ingredient_str.split(" ") while "" in parsed_ingredient: parsed_ingredient.remove("") # print(parsed_ingredient) for i in range(len(parsed_ingredient)): # print(parsed_ingredient) if parsed_ingredient[i] in prepositions: parsed_ingredient = parsed_ingredient[:i] break # print(parsed_ingredient) non_digits = [] for i in range(len(parsed_ingredient)): try: int_check = eval(parsed_ingredient[i]) except: non_digits.append(i) parsed_ingredient[:] = [parsed_ingredient[i] for i in range(len(parsed_ingredient)) if i in non_digits] # get first word # if first word is digit or fraction, eval # "x" not multiplier, "%" used as modulo for i in range(0, len(parsed_ingredient)): plural_unit = check_plurals(parsed_ingredient[i], measurement_units) if plural_unit: del parsed_ingredient[i] if i < len(parsed_ingredient) and parsed_ingredient[i] == "+": while "+" in parsed_ingredient: index = parsed_ingredient.index("+") del parsed_ingredient[index] break # print(parsed_ingredient) for word in parsed_ingredient: if word in unnecessary_words: parsed_ingredient.remove(word) index = 0 while index < len(parsed_ingredient): descriptionString = "" word = parsed_ingredient[index] # search through descriptions (adjectives) if word in descriptions: descriptionString = word # check previous word if index > 0: previous = parsed_ingredient[index - 1] if previous in preceding_words or previous[-2:] == "ly": descriptionString = previous + " " + word parsed_ingredient.remove(previous) # check next_word word elif index + 1 < len(parsed_ingredient): next_word = parsed_ingredient[index + 1] if next_word in succeeding_words or next_word[-2:] == "ly": descriptionString = word + " " + next_word parsed_ingredient.remove(next_word) # word not in descriptions, check if description with predecessor elif word in description_preds and index > 0: descriptionString = parsed_ingredient[index - 1] + " " + word del parsed_ingredient[index - 1] # either add description string to descriptions or check next_word word if descriptionString == "": index+=1 else: parsed_ingredient.remove(word) while "and" in parsed_ingredient: parsed_ingredient.remove("and") if parsed_ingredient[-1] == "or": del parsed_ingredient[-1] for word in parsed_ingredient: for suffix in hyphen_suffixes: if suffix in word: word=word.replace(suffix, "-" + suffix) for prefix in hyphen_prefixes: if word.find(prefix) == 0: word=word.replace(prefix, prefix + "-") if "powder" in parsed_ingredient and \ ("coffee" in parsed_ingredient or \ "espresso" in parsed_ingredient or \ "tea" in parsed_ingredient): parsed_ingredient.remove("powder") ingredient_str = " ".join(parsed_ingredient) if "*" in ingredient_str: ingredient_str.replace("*","") if "," in ingredient_str: ingredient_str.replace(",", "") plural = check_plurals(ingredient_str, all_ingredients) if plural: all_recipe_ingredients.append([recipe_id, plural[0], title, plural[1]]) print("added ingredient {} to recipe {}".format(plural[1].upper(), title.upper())) else: all_ingredients.append([ingredientId_increment, ingredient_str]) all_recipe_ingredients.append([recipe_id, ingredientId_increment, title, ingredient_str]) ingredientId_increment += 1 print("added ingredient {} to recipe {}".format(ingredient_str.upper(), title.upper())) ingredient_count += 1 print("finished writing recipe {}".format(title)) all_recipes.append([recipe_id, title, ingredient_count]) with open("all_ingredients.csv", "w") as f: wr = csv.writer(f) for i in all_ingredients: wr.writerow(i) with open("recipes.csv", "w") as f: wr = csv.writer(f) for r in all_recipes: wr.writerow(r) with open("all_recipe_ingredients.csv", "w") as f: wr = csv.writer(f) for r in all_recipe_ingredients: wr.writerow(r) if __name__== "__main__": main()
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,964
srwei/ezrecipe
refs/heads/master
/ddl/create_tables/load_tables.py
import psycopg2 import csv try: connection = psycopg2.connect(user = "stevenwei", password = "Chicago16", host = "127.0.0.1", port = "5432", database = "ezrecipe") cursor = connection.cursor() try: with open('/Users/stevenwei/Programming/Projects/Personal/ezrecipe/recipes.csv', 'r') as f: reader = csv.reader(f) for row in reader: cursor.execute("INSERT INTO recipes VALUES (%s, %s, %s)", row) print("Successfully inserted into recipe table") except: print("Failed insert into recipe table") try: with open('/Users/stevenwei/Programming/Projects/Personal/ezrecipe/all_ingredients.csv', 'r') as f: reader = csv.reader(f) for row in reader: cursor.execute("INSERT INTO ingredients VALUES (%s, %s)", row) print("Successfully inserted into the ingredients table") except: print("Failed inserting into the ingredients table") try: with open('/Users/stevenwei/Programming/Projects/Personal/ezrecipe/all_recipe_ingredients.csv', 'r') as f: reader = csv.reader(f) for row in reader: cursor.execute("INSERT INTO recipe_ingredients VALUES (DEFAULT, %s, %s, %s, %s)", row) print("Successfully inserted into the recipe ingredients table") except: print("Failed inserting into the recipe ingredients table") connection.commit() # Print PostgreSQL version except (Exception, psycopg2.DatabaseError) as error : print ("Error while creating database to PostgreSQL", error) finally: #closing database connection. if(connection): cursor.close() connection.close() print("PostgreSQL connection is closed")
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,965
srwei/ezrecipe
refs/heads/master
/backend/ezrecipe/apps.py
from django.apps import AppConfig class EzrecipeConfig(AppConfig): name = 'ezrecipe'
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,966
srwei/ezrecipe
refs/heads/master
/ddl/create_tables/create_url_table.py
import psycopg2 try: connection = psycopg2.connect(user = "stevenwei", password = "Chicago16", host = "127.0.0.1", port = "5432", database = "ezrecipe") cursor = connection.cursor() create_url_table_query = "CREATE TABLE urls ( \ recipe_id INTEGER PRIMARY KEY, \ recipe_url TEXT, \ picture_url TEXT \ )" cursor.execute(create_url_table_query) connection.commit() print('Succesfully created URL table') except (Exception, psycopg2.DatabaseError) as error : print ("Error while creating database to PostgreSQL", error) finally: #closing database connection. if(connection): cursor.close() connection.close() print("PostgreSQL connection is closed")
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,967
srwei/ezrecipe
refs/heads/master
/ddl/create_tables/populate_url_table.py
import psycopg2 import csv from bs4 import BeautifulSoup import re import requests try: connection = psycopg2.connect(user = "stevenwei", password = "Chicago16", host = "127.0.0.1", port = "5432", database = "ezrecipe") cursor = connection.cursor() try: with open('/Users/stevenwei/Programming/Projects/django-ezrecipe-react/ddl/src_data/recipes.csv', 'r') as f: reader = csv.reader(f) for row in reader: recipe_id = row[0] recipe_url = "http://www.allrecipes.com/recipe/{}".format(row[0]) response = requests.get(recipe_url) soup = BeautifulSoup(response.text, "html.parser") x = soup.find_all("img", class_= "rec-photo") if x: u = re.findall(r'src="(.*?)"', str(x))[0] picture_url = u if not x: picture_url = "no picture" entry = [recipe_id, recipe_url, picture_url] cursor.execute("INSERT INTO urls VALUES (%s, %s, %s)", entry) #write to csv file next time too just in case job fails before commit print("Populated URLS for {}".format(row[1])) print("Successfully inserted into the ingredients table") except: print("Failed insert URLS recipe table") connection.commit() # Print PostgreSQL version except (Exception, psycopg2.DatabaseError) as error : print ("Error while creating database to PostgreSQL", error) finally: #closing database connection. if(connection): cursor.close() connection.close() print("PostgreSQL connection is closed")
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,968
srwei/ezrecipe
refs/heads/master
/backend/ezrecipe/api.py
from ezrecipe.models import Ingredients, Recipes, RecipeIngredients, InputIngredients from rest_framework import viewsets, permissions, status from .serializers import IngredientsSerializer, RecipesSerializer, RecipeIngredientsSerializer, IngredientsInputSerializer from django.shortcuts import get_object_or_404 from rest_framework.response import Response from rest_framework.views import APIView from bs4 import BeautifulSoup import re import requests #Ingredient Viewset class IngredientsViewSet(viewsets.ModelViewSet): queryset = Ingredients.objects.all() permissions.classes = [ permissions.AllowAny ] serializer_class = IngredientsSerializer #Recipe Viewset class RecipesViewset(viewsets.ModelViewSet): queryset = Recipes.objects.all() permissions.classes = [ permissions.AllowAny ] serializer_class = RecipesSerializer #Recipe Ingredients Viewset class RecipeIngredientsViewset(viewsets.ModelViewSet): queryset = RecipeIngredients.objects.all() permissions.classes = [ permissions.AllowAny ] serializer_class = RecipeIngredientsSerializer class InputIngredientsViewset(viewsets.ModelViewSet): queryset = InputIngredients.objects.all() permissions.classes = [ permissions.AllowAny ] serializer_class = IngredientsInputSerializer def create(self, request): print('#########creating') q = request.data ingredient_list = q["ingredients_str"] ingredient_list = str(ingredient_list).strip('[]') print(ingredient_list) if not ingredient_list: content = {"no ingredients found": "no recipes found"} return Response(content) #x = Recipes.objects.raw("select * f") #for o in x: # print(o.recipe_id) query = """ select r.recipe_id, r.recipe_name, urls.recipe_url, urls.picture_url from recipes r join ( select recipe_id, count(*) as available_ingredients from recipe_ingredients where ingredient_name in ({}) group by recipe_id ) s on r.recipe_id = s.recipe_id join urls on urls.recipe_id = r.recipe_id where s.available_ingredients >= r.num_ingredients """.format(ingredient_list) content = [] r = Recipes.objects.raw(query) print(r) for i in r: print(i.recipe_id, i.recipe_name) print("www.allrecipes.com/recipe/{}".format(i.recipe_id)) recipes = {} recipes["recipe_name"] = i.recipe_name recipes["recipe_url"] = i.recipe_url recipes["picture_url"] = i.picture_url content.append(recipes) #Getting Recipes that are almost available (missing one ingredient) almost_query = """ select r.recipe_id, r.recipe_name, urls.recipe_url, urls.picture_url from recipes r join ( select recipe_id, count(*) as available_ingredients from recipe_ingredients where ingredient_name in ({}) group by recipe_id ) s on r.recipe_id = s.recipe_id join urls on urls.recipe_id = r.recipe_id where s.available_ingredients = r.num_ingredients - 1 """.format(ingredient_list) almost_content = [] aq = Recipes.objects.raw(almost_query) print(aq) for a in aq: print(a.recipe_id, a.recipe_name) print("www.allrecipes.com/recipe/{}".format(a.recipe_id)) almost_recipes = {} almost_recipes["recipe_name"] = a.recipe_name almost_recipes["recipe_url"] = a.recipe_url almost_recipes["picture_url"] = a.picture_url almost_content.append(almost_recipes) json = {"recipes": content, "almost_recipes": almost_content} #print(x) ''' ingredient_list = str(ingredient_list).strip('[]') x = ''' return Response(json)
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,969
srwei/ezrecipe
refs/heads/master
/ddl/create_tables/createdb.py
import psycopg2 try: connection = psycopg2.connect(user = "stevenwei", password = "Chicago16", host = "127.0.0.1", port = "5432", database = "ezrecipe") cursor = connection.cursor() # Print PostgreSQL Connection properties create_recipe_table_query = "CREATE TABLE recipes ( \ recipe_id INTEGER PRIMARY KEY, \ recipe_name TEXT, \ num_ingredients INTEGER \ )" create_ingredients_table_query = "CREATE TABLE ingredients ( \ ingredient_id INTEGER PRIMARY KEY, \ ingredient_name TEXT \ )" create_recipe_ingredients_table_query = "CREATE TABLE recipe_ingredients ( \ recipe_ingredient_id SERIAL PRIMARY KEY, \ recipe_id INTEGER, \ ingredient_id INTEGER, \ recipe_name TEXT, \ ingredient_name TEXT \ )" # Print PostgreSQL version try: cursor.execute(create_recipe_table_query) print("RECIPE table successfully created") except: print("ERROR: Creating RECIPE table failed") try: cursor.execute(create_ingredients_table_query) print("INGREDIENTS table successfully created") except: print("ERROR: Creating INGREDIENTS table failed") try: cursor.execute(create_recipe_ingredients_table_query) print("RECIPE INGREDIENTS table successfully created") except: print("ERROR: Creating RECIPE INGREDIENTS table failed") connection.commit() except (Exception, psycopg2.DatabaseError) as error : print ("Error while creating database to PostgreSQL", error) finally: #closing database connection. if(connection): cursor.close() connection.close() print("PostgreSQL connection is closed")
{"/backend/ezrecipe/urls.py": ["/backend/ezrecipe/api.py", "/backend/ezrecipe/views.py"], "/backend/ezrecipe/views.py": ["/backend/ezrecipe/serializers.py", "/backend/ezrecipe/api.py"], "/backend/ezrecipe/api.py": ["/backend/ezrecipe/serializers.py"]}
74,975
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/layouts.py
import dash_html_components as html import dash_core_components as dcc import dash_daq as daq from GUI.bearingData import bearingFileInfo class Layout: def __init__(self): self.mainPage = html.Div(id = 'mainPage') self.tabOne = html.Div(id = 'tabOne') self.tabTwo = html.Div(id = 'tabTwo') self.dateOpt = [] self.timeOpt = [] def setMainPage(self): #fileinfo_mem = dcc.Store(iid = 'memory-output') #tab_change = html.Div(id = 'tab_change', children = 'foo', style = {'display' : 'none'}) self.mainPage = html.Div( children = [ html.Div(html.H1(children='Bearing Fault Dashboard'), className = 'row'), #tab_change, dcc.Tabs(id="tabs", value='tab1', children=[ dcc.Tab(label = 'Load Data and Draw', value = 'tab1'), dcc.Tab(label = 'Classification', value = 'tab2'), ]), html.Div(id='pages_content', children = self.tabOne), dcc.Store(id = 'dataMem'), dcc.Store(id = 'fileinfoMem') #fileinfo_mem # A space to store something ] ) def setTabOne(self): self.dateOpt,_ = bearingFileInfo() loadfileDiv = html.Div(children = [ dcc.Dropdown( id = 'dateSelect', options = self.dateOpt, value=None, persistence=True, placeholder = 'Select File Date', style={ 'position' : 'relative', 'top' : '10px', #'font-size': '30px', 'text-align' : 'center' } ), dcc.Dropdown( id = 'timeSelect', options=self.timeOpt, value=None, persistence=True, disabled = True, placeholder = 'Select File Time', style={ 'position' : 'relative', 'top' : '10px', #'font-size': '30px', 'text-align' : 'center' } ), dcc.Textarea( id='fileinfo', value='', disabled = True, style={ 'width': '100%', 'height': 200, 'position' : 'relative', 'top' : '60px', 'background-color' : '#f0f0f5' }, persistence = True ), html.Button( 'Load', id='load_btn', style = { 'position' : 'relative', 'top' : '80px', 'left' : '100px', 'background-color' : 'white', 'height' : '80px' } ), ], style = { # 'borderStyle' : 'dashed', 'background-color' : '#e1e1ea', 'height' : '450px', # 'left' : '100px' }, className = 'three columns' ) self.tabOne = html.Div(id = 'tabOne', children = [ html.Div(children = [ loadfileDiv, # the frequence domain file dcc.Graph(id='tmPlot',figure={}, className = 'nine columns')], className = 'row' ), html.Div(children = [ dcc.Graph(id='freqPlot',figure={}), dcc.Graph(id='pwrPlot',figure={}), dcc.Graph(id='autoCorrPlot',figure={})], className = 'row', ) ]) def setTabTwo(self): self.tabTwo = html.Div(id = 'tabTwo', children = [ html.Div(children = [ dcc.Textarea( id='selFileinfo', value='Please select the file first', disabled = True, style={ 'width': '100%', 'height': 200, 'position' : 'relative', 'top' : '60px', 'background-color' : '#f0f0f5' # 'font-family' : 'Courier New' }, persistence = True ), html.Button( 'Classify', id='classify_btn', style = { 'position' : 'relative', 'top' : '110px', 'left' : '100px', 'background-color' : 'white', 'height' : '80px' } )], style = { 'background-color' : '#e1e1ea', 'height' : '450px', }, className = 'three columns'), html.Div( children = [ html.Div( id='faultTypeTxt', children = 'Bearing Fault Type', style = { 'font-size': '26px', #'text-align': 'center' } ), html.Img( id='bearing_img', src='', style = { 'height' : '300px', 'width' : '300px', #'position' : 'relative', #'left' : '50px', #'top' : '120px' }) ], style = { 'position': 'relative', 'top': '80px' }, className = 'four columns'), html.Div( children = [ html.Div( children = '' ), html.Img( id='confusMatrix', src='/home/thl/Documents/Main/GUI/assets/Normal.png', style = { 'height' : '500px', 'width' : '500px', 'position' : 'relative', #'left' : '150px', 'top' : '20px' }) ], className = 'five columns') ], className = 'row')
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,976
nightmare224/BearingProject_GUI
refs/heads/master
/Alog/Header/data_access.py
from Alog.Header.preprocessing import build_feature from Alog.Header.transform import fft, autocorr, normalize import numpy as np from scipy.signal import welch from Alog.Header.transform import * class DataAccess(): def __init__(self, mask_file: str, mask_num: int = 15, wnd: int = 1024, fs: int = 3025): # Parameter: # mask_file: It is a npy file. Its function is filtering the important frequency # mask_num: It is an integer. It will the size of the bandwith # wnd: window size # fs: sample rate # Function: # The constructor just initialize some parameter. It don't do other things. self.display_num = 2 * wnd self.mask = np.load(mask_file) self.mask_num = mask_num self.wnd = wnd self.fs = fs def read_file(self, file_name: str): # Parameter: # file_name: the name of the file # Function: read the data from the file time_arr = self.read(file_name) self.set_val(time_arr) def deal(self, arr): # Parameter: # arr: It must be a list or a numpy.ndarray # Function: read the data from the vector that you give arr = np.asarray(arr) time_arr = self.segment(arr) self.set_val(time_arr) def read(self, file_name): data = np.load(file_name) time_arr = [] if len(data.shape) == 1: # If the data is 1-d array data = data[np.newaxis, :] row, col = data.shape for i in range(row): for j in range(self.wnd, col, self.wnd): #time_norm = normalize(data[i][j: j + wnd]) time_arr.append(data[i][j: j + self.wnd]) time_arr = np.array(time_arr) if (row * col) < 2 * self.wnd: raise ValueError('The size of the input array is too small! It must be bigger than {}.'.format(2 * self.wnd)) return time_arr def preprocessing(self, X): if len(X.shape) == 1: # If the data is 1-d array X = X[np.newaxis, :] row, col = X.shape freq_filter = np.zeros((row, 15)) new_features = np.zeros((row, 10)) for i in range(row): time_norm = normalize(X[i]) freq = fft(time_norm, envelope = False) new_features[i] = build_feature(time_norm, freq) freq_filter[i] = freq[self.mask[:self.mask_num]] all_features = np.concatenate([freq_filter, new_features], axis = 1) return all_features def segment(self, arr): arr = np.asarray(arr) size = len(arr) if size > self.wnd: time_arr = [] for i in range(self.wnd, size, self.wnd): time_arr.append(arr[i: i + self.wnd]) elif size == self.wnd: time_arr = arr else: raise ValueError('The size of the input array is larger than window size, please check!') time_arr = np.array(time_arr) row, col = time_arr.shape if (row * col) < 2 * self.wnd: raise ValueError('The size of the input array is too small ! It must be bigger than {}.'.format(2 * self.wnd)) return time_arr def produce_ploty_data(self, arr): x_freq = np.linspace(0, self.fs // 2, self.display_num//2)[2: ] y_freq = fft(arr, envelope = False)[2: ] x_psd, y_psd = welch(arr, fs = self.fs) y_auto = autocorr(normalize(arr)) x_auto = np.arange(y_auto.shape[0]) return x_freq, y_freq, x_psd, y_psd, x_auto, y_auto def set_val(self, time_arr): self.X = self.preprocessing(time_arr) num = self.display_num // self.wnd self.x_time = np.array([i * (1 / self.fs) for i in range(self.display_num)]) self.y_time = np.concatenate([time_arr[i] for i in range(num)]) self.x_freq, self.y_freq, self.x_psd,\ self.y_psd, self.x_atc, self.y_atc = self.produce_ploty_data(self.y_time) def get_data_for_classifier(self): return self.X def get_data_for_ploty(self): return self.x_time, self.y_time, self.x_freq, self.y_freq, self.x_psd, self.y_psd, self.x_atc, self.y_atc
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,977
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/gui.py
import dash_html_components as html import dash_core_components as dcc from GUI.app import app from GUI.layouts import Layout class GUI: def __init__(self): self.app = app self.app.config['suppress_callback_exceptions'] = True # Create Layout Object self.layout = Layout() # build Layout self.__tabOne__() self.__tabTwo__() self.__mainPage__() def __mainPage__(self): # Config the mainpage self.layout.setMainPage() # Put the Page to app self.app.layout = self.layout.mainPage def __tabOne__(self): self.layout.setTabOne() def __tabTwo__(self): self.layout.setTabTwo()
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,978
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/callbacks.py
import dash from dash.dependencies import Output, Input, State import plotly.graph_objects as go import pandas as pd import numpy as np import time import os from joblib import load from GUI.app import app from GUI.bearingData import bearingFileInfo from Alog.Header.data_access import DataAccess import config # can't not add change tab here, or when change to tab2, here will be trigger too # foo div did not trigger when change tab @app.callback( [Output(component_id = 'timeSelect', component_property = 'options'), Output(component_id = 'timeSelect', component_property = 'disabled')], [Input('dateSelect', 'value')] ) def filedate_select( filedate ): if filedate == None: return [], True else: _, timedict = bearingFileInfo() timelist = [] for time in timedict[filedate]: timelist.append({'label':time, 'value':time}) return timelist, False @app.callback( [ Output(component_id = 'fileinfo', component_property = 'value'), Output(component_id = 'fileinfoMem', component_property = 'data') ], [Input('timeSelect', 'value')], [State('dateSelect', 'value')] ) def filetime_select( filetime, filedate ): #print('cometime = ', filedate, filetime) if filetime is None: return '', {} else: fileinfo = 'File Datatime : {}\n\nData Size : {:.2f} MB\n\n'.format( filedate + ' ' + filetime , 1.2) return fileinfo, fileinfo @app.callback( [ Output(component_id = 'tmPlot', component_property = 'figure'), Output(component_id = 'freqPlot', component_property = 'figure'), Output(component_id = 'pwrPlot', component_property = 'figure'), Output(component_id = 'autoCorrPlot', component_property = 'figure'), Output(component_id = 'dataMem', component_property = 'data') ], [Input('load_btn', 'n_clicks')], [State('dateSelect', 'value'), State('timeSelect', 'value')] ) def load_file(loadbtn_clicksno, filedate, filetime): if loadbtn_clicksno is None: return {}, {}, {}, {}, {} filename = filedate + '_' + filetime dataObj = DataAccess(config.maskFile) dataObj.read_file(config.DatabasePath + filename + '.npy') x_time, y_time, x_freq, y_freq, x_psd, y_psd, x_atc, y_atc = dataObj.get_data_for_ploty() # plot figure of the file tmPlot = drawTmPlot(x_time, y_time) freqPlot = drawFreqPlot(x_freq, y_freq) pwrPlot = drawPwrPlot(x_psd, y_psd) autoCorrPlot = drawAutoCorrPlot(x_atc, y_atc) # data for classify x = dataObj.get_data_for_classifier() return tmPlot, freqPlot, pwrPlot, autoCorrPlot, x def drawTmPlot(xt, yt): fig = go.Figure( data = go.Scatter( x=xt, y=yt, mode='lines')) fig.update_layout(title='Time Domain', xaxis_title='t (sec)', yaxis_title='', showlegend=False) return fig def drawFreqPlot(xf, yf): fig = go.Figure( data = go.Scatter( x=xf, y=yf, mode='lines')) fig.update_layout(title='Frequency Domain', xaxis_title='f (Hz)', yaxis_title='', showlegend=False) return fig def drawPwrPlot(xp, yp): fig = go.Figure( data = go.Scatter( x=xp, y=yp, mode='lines')) fig.update_layout(title='Power Spetral Density', xaxis_title='f (Hz)', yaxis_title='', showlegend=False) return fig def drawAutoCorrPlot(xa, ya): fig = go.Figure( data = go.Scatter( x=xa, y=ya, mode='lines')) fig.update_layout(title='Autocorrelation', xaxis_title='t (sec)', yaxis_title='', showlegend=False) return fig @app.callback( [ Output(component_id = 'bearing_img', component_property = 'src'), Output(component_id = 'faultTypeTxt', component_property = 'children'), ], [Input('classify_btn', 'n_clicks')], [State(component_id = 'dataMem', component_property = 'data')] ) def classify(n_clicks, data): faultType = ['Inner_Break', 'Outer_Break', 'Cage_Break', 'Normal'] if ( n_clicks is None ) or ( data == {} ) : return app.get_asset_url('NoImage.png'), 'Bearing Fault Type' # load model rfModel = load(config.ModelFile) result = rfModel.predict(data) #unq, cnt = np.unique(result, return_counts = True) #result = unq[np.argmax(cnt)] # choose first result result = result[0] # fault type name faultTypeTxt = faultType[result].replace('_', ' ') faultTypeTxt = 'Bearing Fault Type - {}'.format(faultTypeTxt) return app.get_asset_url(faultType[result] + '.png'), faultTypeTxt @app.callback( [Output(component_id = 'selFileinfo', component_property = 'value')], [Input('tabs', 'value')], [ State(component_id = 'dataMem', component_property = 'data'), State(component_id = 'fileinfoMem', component_property = 'data') ] ) def updateFileinfo(foo, dataMem, fileinfo): # file not select yet if dataMem == {}: return 'Please select the file first', else: return fileinfo, @app.callback( Output(component_id = 'confusMatrix', component_property = 'src'), Input('confusMatrix', 'id') ) def uploadConfusMatrix(foo): return app.get_asset_url('confusionMatrix.png')
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,979
nightmare224/BearingProject_GUI
refs/heads/master
/Alog/Header/preprocessing.py
import numpy as np import pandas as pd from scipy.stats import skew, kurtosis from scipy.signal import hilbert, welch, savgol_filter from Alog.Header.transform import * # Global var for ploty freq_auto, autocorr, freq_psd, psd = 0, 0, 0, 0 def build_feature(time_arr, freq_arr): N = time_arr.shape[0] # build time domain feature Mean = np.mean(time_arr) Std = np.std(time_arr) Peak = 0.5 * (np.max(time_arr) - np.min(time_arr)) RMS = np.sqrt(np.sum([ i ** 2 for i in time_arr])) Kurtosis = kurtosis(time_arr) Skew = skew(time_arr) Crest = Peak / RMS tmp = np.array([np.sqrt(np.abs(i)) for i in time_arr]) Clearance = Peak / ((1 / N) * np.sum(tmp)) ** 2 Allowance = Peak / np.mean(tmp) ** 2 tmp = ((1 / N) * np.sum([np.abs(i) for i in time_arr])) Impulse = Peak / tmp Shape = RMS / tmp # build freq domain feature N = freq_arr.shape[0] st = 1e-2 fs = 1 / st y = 2 * freq_arr / N f = np.array([(i + 1.) * fs / N for i in range(N)]) F_Mean = np.mean(y) F_Std = np.std(y) FC = np.dot(f, y) / np.sum(y) MSF = np.dot(np.multiply(f, f), y) / np.sum(y) RMSF = np.sqrt(MSF) VF = np.dot(np.multiply(f - FC, f - FC),y)/ np.sum(y) RVF = np.sqrt(VF) return [Mean, Std, Peak, RMS, Skew, F_Mean, F_Std, FC, RMSF, RVF] def outlier_detect_Isolation_Forest(data, percentage = 0.1): IF = IsolationForest(n_estimators=200, max_samples='auto', contamination=percentage, max_features=1.0, bootstrap=True, n_jobs=None, random_state=12, verbose=0, warm_start=False) IF.fit(data) outlier = IF.predict(data) mask = np.where(outlier == 1)[0] return mask def read_file(file_name, wnd = 256, n = None): data = np.load(file_name) row, col = data.shape if n == None: pass elif n > row: raise ValueError("The number of data is too low to read. Please check data num") else: row = n time_arr = [] for i in range(row): for j in range(wnd, col, wnd): time_arr.append(data[i][j: j + wnd]) time_arr = np.array(time_arr) return time_arr def read_train_file(file_lst, name_lst, n = 10, wnd = 256): # | file_lst: [檔名1, 檔名2, ...] # | name_lst: key 的名字 # | n: 每個類別有幾筆 4096 的資料 # | wnd: window size # | outlier_detect_mode: 0 -> no outlier detection, 1 -> moving average, 2 -> Isolation Forest, 3 -> both # | the parameter for moving average # | lower: # | upper: # | the parameter for Isolation Forest data = dict() for i, name in enumerate(file_lst): # 取得資料 data[name_lst[i]] = np.load(name) mag_arr = [] time_arr = [] label = [] for i, name in enumerate(name_lst): for j in range(n): for k in range(wnd, data[name].shape[1], wnd): time = data[name][j][k: k + wnd] time_arr.append(time) label.append(i) time_arr = np.array(time_arr) label = np.array(label) return time_arr, label def preprocessing( X, fs = 2048, normalize = True, smooth = False, preprocessing_mode = 'fft', envelope = False, first_n_peaks = 10, height = 0, mask = True, mask_num = 15 ): # -------------------------- # | X: time domain data # | Y: the label of the data # | # | preprocessing_mode: # | It is a list. Ex. preprocessing_mode = ['fft', 'construct'] # | 1. time (no preprocessing) # | 2. construct (14 features), (construct some features by time domain and freq domain) # | 3. fft (mask_num features), (Fourier Transform), # | 4. psd (first_n_peaks features), (Power Spectral Density) # | 5. autocorrelation (first_n_peaks features) # | # | envelope: time -> hilbert -> fft # | # | outlier_mode: # | 1. 0: no outlier detection # | 2. 1: Isolaiton Forest # | # | percentage: # | How many oulier do you want to remove? # | It is a number between [0, 1], default is 0.1. # -------------------------- data = dict() preprocessing_mode = [mode.lower() for mode in preprocessing_mode] time_arr = X.copy() row, col = X.shape if normalize: if len(time_arr.shape) == 1: time_arr = (time_arr - np.mean(time_arr)) / np.std(time_arr) else: for i in range(row): time_arr[i] = (time_arr[i] - np.mean(time_arr[i])) / np.std(time_arr[i]) if smooth: for i in range(row): time_arr[i] = savgol_filter(time_arr[i], window_length = 5, polyorder = 3) new_features = np.zeros((row, 10)) flag = 0 if 'time' in preprocessing_mode: return X if 'fft' in preprocessing_mode: freq_spectrum = np.zeros((row, col // 2)) for i in range(row): freq_spectrum[i] = fft(time_arr[i], envelope = envelope) new_features[i] = build_feature(time_arr[i], freq_spectrum[i]) if mask: mask = np.load('./feature_importance_mask/mask_wnd_1024.npy') freq_spectrum = freq_spectrum[:, mask[:mask_num]] data['fft'] = freq_spectrum flag += 1 if 'construct' in preprocessing_mode: if 'fft' not in preprocessing_mode: for i in range(row): freq = fft(time_arr[i], envelope = envelope) new_features[i] = build_feature(time_arr[i], freq) flag += 1 data['construct'] = new_features flag += 1 if 'psd' in preprocessing_mode: psd_peak = np.zeros((row, first_n_peaks)) for i in range(row): freq_psd, psd = welch(time_arr[i], fs = 2048) psd_peak[i], _ = get_first_n_peaks(psd, first_n_peaks, height) data['psd'] = psd_peak flag += 1 if 'autocorrelation' in preprocessing_mode: # auto_peak = np.zeros((row, first_n_peaks)) auto_peak = np.zeros((row, 2)) for i in range(row): autocorr = get_autocorr_values(time_arr[i], N = col, f_s = fs) # auto_peak[i], _ = get_first_n_peaks(autocorr, first_n_peaks, height) auto_peak[i] = get_atc_corr_intercept(autocorr) data['autocorrelation'] = auto_peak flag += 1 if flag == 0: raise ValueError("I don't know what you mean ?") all_features = np.concatenate([data[mode] for mode in preprocessing_mode], axis = 1) return all_features def outlier_detection(X, Y, outlier_mode = 0, percentage = 0.1): if outlier_mode == 1: mask = outlier_detect_Isolation_Forest(X, percentage = percentage) X_inlier = X[mask] Y_inlier = Y[mask] return X_inlier, Y_inlier def train_test_split_by_time(x, y, test_size): class_num = np.unique(y).shape[0] x_train = [] x_test = [] y_train = [] y_test = [] for i in range(class_num): mask = np.where(y == i)[0] train_size = int(mask.shape[0] * (1 - test_size)) # print('HiHi', train_size) # print(mask[:10]) for j in mask[: train_size]: x_train.append(x[j]) y_train.append(y[j]) for j in mask[train_size: ]: x_test.append(x[j]) y_test.append(y[j]) x_train, y_train = shuffle(np.array(x_train), np.array(y_train)) x_test, y_test = shuffle(np.array(x_test), np.array(y_test)) return x_train, x_test, y_train, y_test
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,980
nightmare224/BearingProject_GUI
refs/heads/master
/main.py
from GUI.gui import GUI from GUI import callbacks from GUI.app import app from dash.dependencies import Output, Input, State ## create the GUI gui = GUI() ## ugly part..., for rendering the tab content, ## because there is no other part can get layout instant, ## so put this callback func here### @app.callback( [Output('pages_content', 'children')], [Input('tabs', 'value')] ) def renderContent(tab): if tab == 'tab1': return gui.layout.tabOne, else: return gui.layout.tabTwo, if __name__ == '__main__': gui.app.run_server(host = '0.0.0.0', debug = False)
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,981
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/plot.py
import plotly.express as px import pandas as pd import numpy as np fig = px.line(data, title = 'Time Domain')
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,982
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/app.py
import dash # add in persistence=True dcc to prevent refresh while switching https://dash.plotly.com/persistence external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # assume you have a "long-form" data frame # see https://plotly.com/python/px-arguments/ for more options
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,983
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/callbacks.py
import dash import dash_html_components as html from dash.dependencies import Output, Input, State import plotly.express as px import pandas as pd import numpy as np import time import os # # outlier detect # from sklearn.ensemble import IsolationForest from app import app from bearingData import bearingFileInfo # file upload and show file information app.config['suppress_callback_exceptions'] = True # can't not add change tab here, or when change to tab2, here will be trigger too # foo div did not trigger when change tab @app.callback( [Output(component_id = 'timeSelect', component_property = 'options'), Output(component_id = 'timeSelect', component_property = 'disabled')], [Input('dateSelect', 'value')] ) def filedate_select( filedate ): print('come date') if filedate == None: print('here') return [], True else: _, timedict = bearingFileInfo() timelist = [] for time in timedict[filedate]: timelist.append({'label':time, 'value':time}) return timelist, False @app.callback( [Output(component_id = 'fileinfo', component_property = 'value'), Output(component_id = 'memory-output', component_property = 'data')], [Input('timeSelect', 'value')], [State('dateSelect', 'value')] ) def filetime_select( filetime, filedate ): print('cometime = ', filedate, filetime) if filetime is None: return '', {} else: fileinfo = 'File Datatime : {}\n\nData Size : {:.2f} MB\n\n'.format( filedate + ' ' + filetime , 1.2) return fileinfo, {} # @app.callback( # # the instant name and instant value # # [Output(component_id = 'fileinfo', component_property = 'children')], # [Output(component_id = 'fileinfo', component_property = 'value'), Output(component_id = 'memory-output', component_property = 'data')], # [Input('tab_change', 'children'), Input('bearing_file_upload', 'contents')], # [State('bearing_file_upload', 'filename'), State('bearing_file_upload', 'last_modified'), State(component_id = 'memory-output', component_property = 'data')] # ) # def upload_file(foo, contents, filename, filedates, fileinfo_mem): # # print(foo, filename, fileinfo_mem) # # filename will be None when switch the tab # # fileinfo_mem will be None initially # if (filename is not None) and (filename.endswith('.npy') | filename.endswith('.csv') | filename.endswith('.xlsx')): # fileinfo_dict = {'Filename' : filename, 'Last Modified': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(filedates)),\ # 'Data Size' : os.stat('./Formal/'+filename)[-4]/1024/1024} # elif (fileinfo_mem != {}) & (fileinfo_mem is not None): # fileinfo_dict = fileinfo_mem # else: # # add new branceh : filetype not support in future # return '', {} # fileinfo = 'Filename : {}\n\nLast Modified : {}\n\nData Size : {:.2f} MB\n\n'.format( # fileinfo_dict['Filename'], fileinfo_dict['Last Modified'], fileinfo_dict['Data Size']) # return fileinfo, fileinfo_dict # 可以用state當input, 去取得某個物件的狀態 # @app.callback( # [Output(component_id = 'fileinfo_page2', component_property = 'value')], # [Input('memory-output', 'data')], # ) # def update_page2(fileinfo_dict): # # print(data) # fileinfo = 'Filename : {}\n\nLast Modified : {}\n\nData Size : {:.2f} MB\n\n'.format( # fileinfo_dict['Filename'], fileinfo_dict['Last Modified'], fileinfo_dict['Data Size']) # return fileinfo, @app.callback( [ Output(component_id = 'fig1', component_property = 'figure'), Output(component_id = 'fig2', component_property = 'figure'), Output(component_id = 'fig3', component_property = 'figure')], [Input('load_btn', 'n_clicks')], [State('dateSelect', 'value'), State('timeSelect', 'value')] ) def load_file(loadbtn_clicksno, filedate, filetime): if loadbtn_clicksno is None: return {}, {}, {} filename = filedate + '_' + filetime # read file # if filename is None: # return {},{},{} # elif filename.endswith('.npy'): # sourcefile = np.load('./Formal/'+filename) # elif filename.endswith('.csv'): # sourcefile = pd.read_csv(filename) # elif filename.endswith('.xlsx'): # sourcefile = pd.read_excel(filename) # else: # print('Filetype Not Support') # return None, # format file mainfile = np.array(sourcefile).reshape(-1) if outlier_detect_en: mainfile = drop_outlier(mainfile) # plot figure of the file fig1 = drawGraph(0, mainfile) fig2 = drawGraph(1, mainfile) fig3 = drawGraph(2, mainfile) #return fig1, fig2, fig3 # get two plot return get_preprocess_plot([filename], [filename]) @app.callback( [Output(component_id = 'bearing_img', component_property = 'src')], [Input('classify_btn', 'n_clicks')], [State(component_id = 'memory-output', component_property = 'data')] ) def classify(n_clicks, fileinfo_mem): if ( n_clicks != None ) & (fileinfo_mem != {}) & (fileinfo_mem is not None): # 暫時寫死, 考檔名分類, 之後要改成演算法 return app.get_asset_url(fileinfo_mem['Filename'][:-4] + '.png'), else: return None, def drawGraph(opt, mainfile): data = mainfile.copy() # print(mainfile.shape) # time domain if opt == 0: data = data[:4096] fig = px.line(data, title = 'Time Domain') # frquence domain elif opt == 1: # data = data[:2000] fdata = np.fft.fft(data) x = fdata.real y = abs(fdata) fig = px.scatter(x,y, title = 'Frequence Domain') # envelope elif opt == 2: data = data[:1000] fig = px.line(data, title = 'Envelope Curve') # print(data) # must add comma, to be an tuple return fig # @app.callback( # [ # Output(component_id = 'fig1', component_property = 'figure'), # Output(component_id = 'fig2', component_property = 'figure'), # Output(component_id = 'fig3', component_property = 'figure')] # [Input('bearing_file_upload', 'contents')], # [State('bearing_file_upload', 'filename'), State('bearing_file_upload', 'last_modified')]) # ) # def update_figs(): # return {}, {}, {} def drop_outlier(data): mask = [] different = [] datas = data.reshape(-1,128) for tmp in datas: different.append(abs(np.max(tmp)-np.min(tmp))) different = np.array(different) lower, upper = np.percentile(different, [10,90]) mask = (different >= lower) & (different <= upper) datas = datas[mask] # data = data.copy() # IF = IsolationForest() # IF.fit(data.reshape(-1,1)) # outlier = IF.predict(data.reshape(-1,1)) # data = data[outlier==1] return datas.reshape(-1)
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,984
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/bearingData.py
from path import dateinfoPath ### date information ### def bearingFileInfo(): datefile = open(dateinfoPath + 'dateinfo', "r") datelist_tmp = [] timedict = {} for line in datefile: date, time = line.split('_') if date in datelist_tmp: timedict[date].append(time) else: datelist_tmp.append(date) timedict[date] = [time] datelist = [] for date in datelist_tmp: datelist.append({'label':date, 'value':date}) datefile.close() return datelist, timedict
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,985
nightmare224/BearingProject_GUI
refs/heads/master
/Alog/Header/visualize.py
import matplotlib.pyplot as plt from IPython.display import Image from sklearn import tree import pydotplus from IPython.display import Image import numpy as np def plot_tree(clf, feature_name, class_name): dot_data = tree.export_graphviz( clf, out_file = None, feature_names = feature_name, class_names = class_name, filled = True, rounded = True, special_characters = True ) graph = pydotplus.graph_from_dot_data(dot_data) graph = Image(graph.create_png()) return graph def plot_signal(x, y, x_label, y_label, title, figsize = (20, 5), bar = False): plt.figure(figsize = figsize) plt.title(label = title, fontdict = {'fontsize': 15}) if bar: plt.bar(x, y, width=0.8) else: plt.plot(x, y) plt.xlabel(x_label, fontdict = {'fontsize': 12}) plt.ylabel(y_label, fontdict = {'fontsize': 15}) plt.show()
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,986
nightmare224/BearingProject_GUI
refs/heads/master
/config.py
DatabasePath = '/home/thl/Documents/Database/' DatabaseInfoPath = '/home/thl/Documents/Database/info/' # preprocessing parameter maskFile = '/home/thl/Documents/Main/Alog/feature_importance_mask/mask_wnd_1024.npy' BearingImgPath = '/home/thl/Documents/Main/GUI/assets/' ModelFile = '/home/thl/Documents/Main/Alog/model/rf_fft_construct.model'
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,987
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/gui.py
import dash import dash_core_components as dcc import dash_daq as daq import dash_html_components as html from dash.dependencies import Output, Input, State import plotly.express as px import pandas as pd import numpy as np import time import os # # outlier detect # from sklearn.ensemble import IsolationForest from app import app from layouts import page1_div, page2_div, page3_div, fileinfo_mem, tab_change mainfile = np.load('./Formal/Cage_Break.npy').reshape(-1) fig1 = px.line(mainfile, title = 'Frequency Domain') fig2 = px.line(mainfile, title = 'Envolope') # fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group") app.config['suppress_callback_exceptions'] = True app.layout = html.Div(children=[ html.Div(html.H1(children='Bearing Fault Dashboard'), className = 'row'), # the style here is internal CSS style # example : <h1 style="text-align:center;color:red">......</h1> # html.Div(children=' Dash: A web application framework for Python.', # style = {'text-align':'center','color':'red'}, className = 'row'), tab_change, dcc.Tabs(id="tabs", value='tab1', children=[ dcc.Tab(label = 'Load Data and Draw', value = 'tab1'), dcc.Tab(label = 'Classification', value = 'tab2'), dcc.Tab(label = 'Database', value = 'tab3') ]), html.Div(id='pages_content', children = page1_div), # a html.Div fileinfo_mem, # just for notify tab is changing ]) @app.callback( [Output('pages_content', 'children'), Output('tab_change', 'children')], [Input('tabs', 'value')] ) def render_content(tab): if tab == 'tab1': return page1_div,'foo1' elif tab == 'tab2': return page2_div, 'foo2' elif tab == 'tab3': return page3_div, 'foo3' if __name__ == '__main__': app.run_server(host = '0.0.0.0', debug=True) # app.run_server(debug=True)
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,988
nightmare224/BearingProject_GUI
refs/heads/master
/Alog/Header/transform.py
import numpy as np import pandas as pd from scipy.signal import hilbert, welch import matplotlib.pyplot as plt def getEnvelope (data): env = np.abs(hilbert(data)) return env def normalize(data): a = data.copy() a = (a - np.mean(a)) / np.std(a) return a def fft(arr, envelope = True): # -------------------------- # | Parameter: # | arr: Please input an 1darray, list, or series. # | envelope: time -> hilbert -> fft # -------------------------- # -------------------------- # | Return: # | out: freq spectrum # -------------------------- arr = np.asarray(arr, dtype = 'float64') if envelope: arr = getEnvelope(arr) # 左右對稱 -> 取一半的資料 FFT = np.fft.fft(arr, norm='ortho')[:len(arr)//2] # get magnitude FFT = np.abs(FFT) return FFT def get_first_n_peaks(data, n, height = 0): if n > data.shape[0]: raise ValueError('first_n_peaks > peak_location, please check.') if height == 'auto': mean = np.mean(data) std = np.std(data) height = mean + 3 * std peaks_location, peaks_val = find_peaks(data, height = height) peaks_val = peaks_val['peak_heights'] exc = 2 if ((peaks_location.shape[0]) - n) < exc: fill = n - peaks_location.shape[0] + exc peaks_location = np.array(peaks_location.tolist() + [0 for _ in range(fill)]) peaks_val = np.array(peaks_val.tolist() + [0 for _ in range(fill)]) return peaks_location[exc: (n + exc)], peaks_val[1: (n + 1)] def autocorr(x): result = np.correlate(x, x, mode='full') return result[len(result)//2:] def get_autocorr_values(y_values, N, f_s): # y_values = (y_values - np.mean(y_values)) / np.std(y_values) autocorr_values = autocorr(y_values) # autocorr_values += np.abs(autocorr_values) return autocorr_values def get_atc_corr_intercept(y): r = np.corrcoef(y) i = np.max(y) return r, i
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,989
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/layouts.py
import dash import dash_core_components as dcc import dash_daq as daq import dash_html_components as html from datetime import datetime as dt from app import app import callbacks from bearingData import bearingFileInfo # global dateopt,_ = bearingFileInfo() fileinfo_mem = dcc.Store(id = 'memory-output') tab_change = html.Div(id = 'tab_change', children = 'foo', style = {'display' : 'none'}) loadfile_div = \ html.Div(children = [ ######### Enable dateselect when database is done # dcc.DatePickerSingle( # id='date-picker-single', # date=dt(2020, 9, 1), # style = { # 'font-family' : 'Courier New' # } # ), # dcc.Upload( # id = 'bearing_file_upload', # children = html.Div( ['Drag and Drop or ', html.A('Select Files')], style = {'position' : 'relative','top':'14px'} ), # multiple = False, # style = { # 'position' : 'relative', # 'top' : '40px', # 'left' : '20px', # 'width' : '250px', # 'height' : '60px', # 'textAlign': 'center', # 'borderStyle' : 'dashed', # 'background-color' : '#ffffff', # 'font-style': 'italic', # 'font-weight' : 'bold' # } # ), dcc.Dropdown( id = 'dateSelect', options = dateopt, value=None, persistence=True, placeholder = 'Select File Date', style={ 'position' : 'relative', 'top' : '10px', #'font-size': '30px', 'text-align' : 'center' } ), dcc.Dropdown( id = 'timeSelect', options=[], value=None, persistence=True, disabled = True, placeholder = 'Select File Time', style={ 'position' : 'relative', 'top' : '10px', #'font-size': '30px', 'text-align' : 'center' } ), # html.Div(id = 'fileinfo', children = [ # dcc.Markdown(''' # #### Dash and Markdown # Dash supports [Markdown](http://commonmark.org/help). # Markdown is a simple way to write and format text. # It includes a syntax for things like **bold text** and *italics*, # [links](http://commonmark.org/help), inline `code` snippets, lists, # quotes, and more. # ''')], # style = { # 'position' : 'relative', # 'top' : '60px', # 'background-color' : '#f0f0f5', # 'width' : '280px', # 'height' : '200px', # 'left' : '15px', # # 'font-family' : 'Courier New' # # 'text-align' : 'center' # } # ), dcc.Textarea( id='fileinfo', value='', disabled = True, style={ 'width': '100%', 'height': 200, 'position' : 'relative', 'top' : '60px', 'background-color' : '#f0f0f5' }, persistence = True ), html.Button('Load', id='load_btn', style = { 'position' : 'relative', 'top' : '80px', 'left' : '200px', 'background-color' : 'white', 'height' : '80px' } ), # dcc.RadioItems( # options=[ # {'label': 'Origianl', 'value': '0'}, # {'label': 'Drop Outlier', 'value': '1'} # ], # value='0', # labelStyle={'display': 'inline-block'}, # style = { # 'position' : 'relative', # 'top' : '30px', # 'left' : '10px' # } # ) # relative : compare with original position daq.BooleanSwitch( id='outlier_detect', label = 'Enable Outlier Detection', labelPosition = 'top', on=False, persistence = True, style = { 'position' : 'relative', 'top' : '0px', 'right' : '50px', # 'font-family' : 'Courier New' } ) ], style = { # 'borderStyle' : 'dashed', 'background-color' : '#e1e1ea', 'height' : '450px', # 'left' : '100px' }, className = 'three columns' ) page1_div =\ html.Div(id = 'page1', children = [ html.Div(children = [ loadfile_div, # the frequence domain file dcc.Graph(id='fig1',figure={}, className = 'nine columns')], className = 'row' ), # {'data' : ...., 'layout' : .....} html.Div(children = [ # html.Div(children = dcc.Graph(figure=fig, className = 'four columns')), dcc.Graph(id='fig2',figure={}, className = 'six columns'), dcc.Graph(id='fig3',figure={}, className = 'six columns')], className = 'row', )] ) page2_div =\ html.Div(id = 'page2', children = [ html.Div(children = [ html.Div(children = [ dcc.Dropdown( options=[ {'label': '500 RPM', 'value': '500'}, {'label': '1000 RPM', 'value': '1000'}, {'label': '2000 RPM', 'value': '2000'} ], value='500', style = { 'position' : 'relative', 'top' : '20px', 'left' : '20px', 'width' : '250px', 'height' : '60px', 'textAlign': 'center', # 'background-color' : '#ffffff', } ), dcc.Textarea( id='fileinfo', value='Textarea content initialized\nwith multiple lines of text', disabled = True, style={ 'width': '100%', 'height': 200, 'position' : 'relative', 'top' : '60px', 'background-color' : '#f0f0f5' # 'font-family' : 'Courier New' }, persistence = True ), html.Button('Classify', id='classify_btn', style = { 'position' : 'relative', 'top' : '80px', 'left' : '160px', 'background-color' : 'white', 'height' : '80px' } )], style = { # 'borderStyle' : 'dashed', 'background-color' : '#e1e1ea', 'height' : '450px', }, className = 'three columns' ), html.Img( id='bearing_img', src = '', className = 'six columns', style = { 'height' : '300px', 'width' : '300px', 'position' : 'relative', 'left' : '300px', 'top' : '80px' } ), # foo dcc.Upload( id = 'bearing_file_upload', style = {'display' : 'none'} ) # not fit layout # html.Div('',style = { # 'weight' : '10px', # 'height' : '600px', # 'background-color' : '#e6f3ff' # }) ], # dcc.Graph(id='fig1',figure={}, className = 'nine columns')], className = 'row' ) ]) page3_div =\ html.Div(id = 'page3', children = [ # foo Div, just for switching tab html.Div(id = 'bearing_file_upload' ,style = {'display' : 'none'}), html.Div(id = 'fileinfo', style = {'display' : 'none'}) ])
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
74,990
nightmare224/BearingProject_GUI
refs/heads/master
/GUI/backup/path.py
dateinfoPath = '/home/thl/Documents/Database/info/'
{"/Alog/Header/data_access.py": ["/Alog/Header/preprocessing.py", "/Alog/Header/transform.py"], "/GUI/gui.py": ["/GUI/layouts.py"], "/GUI/callbacks.py": ["/Alog/Header/data_access.py", "/config.py"], "/Alog/Header/preprocessing.py": ["/Alog/Header/transform.py"], "/main.py": ["/GUI/gui.py"]}
75,022
SoheeLee/swpp17-team12
refs/heads/master
/backend/adfreereview/urls.py
from django.conf.urls import url, include from .views import myModelList from .views import signup, signin, signout from .views import token urlpatterns = [ url(r'^mymodel$', myModelList, name='myModelList'), url(r'^signup$', signup, name='signup'), url(r'^signin$', signin, name='signin'), url(r'^signout$', signout, name='signout'), url(r'^token$', token, name='token'), ]
{"/backend/adfreereview/urls.py": ["/backend/adfreereview/views.py"]}
75,023
SoheeLee/swpp17-team12
refs/heads/master
/backend/adfreereview/admin.py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from .models import MyModel from .models import Profile # Register your models here. # Define an inline admin descriptor for Profile model # which acts a bit like a singleton # https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#extending-the-existing-user-model # https://simpleisbetterthancomplex.com/tutorial/2016/11/23/how-to-add-user-profile-to-django-admin.html class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'Profile' fk_name = 'user' # Define a new User admin class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'get_score') list_select_related = ('profile', ) def get_score(self, instance): return instance.profile.score get_score.short_description = 'Score' def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, CustomUserAdmin)
{"/backend/adfreereview/urls.py": ["/backend/adfreereview/views.py"]}
75,024
SoheeLee/swpp17-team12
refs/heads/master
/backend/adfreereview/views.py
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseNotFound, JsonResponse from django.views.decorators.csrf import ensure_csrf_cookie from .models import MyModel from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout import json # Create your views here. def myModelList(request): if request.method == 'GET': return JsonResponse(list(MyModel.objects.all().values()), safe=False) else: return HttpResponseNotAllowed(['GET']) def signup(request): if request.method == 'POST': req_data = json.loads(request.body.decode()) username = req_data['username'] email = req_data['email'] password = req_data['password'] User.objects.create_user(username=username, email=email, password=password) return HttpResponse(status=201) else: return HttpResponseNotAllowed(['POST']) def signin(request): if request.method == 'POST': req_data = json.loads(request.body.decode()) username = req_data['username'] password = req_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse(status=200) else: return HttpResponse(status=401) else: return HttpResponseNotAllowed(['POST']) def signout(request): if request.method == 'GET': logout(request) return HttpResponse(status=200) else: return HttpResponseNotAllowed(['GET']) @ensure_csrf_cookie def token(request): if request.method == 'GET': return HttpResponse(status=204) else: return HttpResponseNotAllowed(['GET'])
{"/backend/adfreereview/urls.py": ["/backend/adfreereview/views.py"]}
75,025
Abdulla-binissa/sudoku.py
refs/heads/main
/SudokuEngine.py
import random class Gamestate(): def __init__(self): self.board = [ ['1', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'], ['?', '?', '?', '?', '?', '?', '?', '?', '?'] ] self.givenSquares = {} def generateNewSudoku(self): #for row in range( 0, len(self.board) ): # for col in range( 0, len(self.board) ): # string = str(random.randint(1, 9)) # self.board[row][col] = string self.board = [ ['8', '9', '?', '7', '?', '4', '?', '?', '?'], ['2', '3', '?', '?', '?', '?', '?', '?', '9'], ['?', '?', '7', '?', '?', '?', '5', '3', '?'], ['9', '4', '?', '?', '5', '1', '?', '?', '6'], ['?', '7', '8', '?', '2', '6', '?', '4', '?'], ['?', '?', '?', '4', '?', '3', '?', '?', '1'], ['7', '?', '4', '?', '?', '8', '?', '1', '?'], ['?', '?', '?', '3', '?', '?', '?', '?', '?'], ['?', '?', '6', '?', '?', '?', '2', '?', '?'] ] self.givenSquares = { (0,0),(0,1),(0,3),(0,5), (1,0),(1,1),(1,8), (2,2),(2,6),(2,7), (3,0),(3,1),(3,4),(3,5),(3,8), (4,1),(4,2),(4,4),(4,5),(4,7), (5,3),(5,5),(5,8), (6,0),(6,2),(6,5),(6,7), (7,3), (8,2),(8,6) } self.conflictingSquares = [] def isEmptySpot(self, squareSelected): if(self.board[squareSelected[0]][squareSelected[1]] == '?'): return True else: return False def isPlayableSpot(self, squareSelected): if( self.givenSquares.__contains__(squareSelected) ): return False else: return True def setSpot(self, number, squareSelected): self.board[squareSelected[0]][squareSelected[1]] = number def checkQuadrant(self, squareSelected): squareValue = self.board[squareSelected[0]][squareSelected[1]] if squareValue == "?": return value = False for r in range(0, 3): for c in range(0, 3): testRow = (squareSelected[0] // 3)*3 + r testCol = (squareSelected[1] // 3)*3 + c if (squareSelected[0] == testRow and squareSelected[1] == testCol): continue testSquareValue = self.board[testRow][testCol] if( squareValue == testSquareValue ): if not self.conflictingSquares.__contains__((squareSelected[0], squareSelected[1])): self.conflictingSquares.append((squareSelected[0], squareSelected[1])) if not self.conflictingSquares.__contains__((testRow, testCol)): self.conflictingSquares.append((testRow, testCol)) value = True return value def checkLines(self, squareSelected): squareValue = self.board[squareSelected[0]][squareSelected[1]] testRow = squareSelected[0] value = False for testCol in range(0, 9): testSquareValue = self.board[testRow][testCol] if (squareSelected[0] == testRow and squareSelected[1] == testCol): continue if( squareValue == testSquareValue ): if not self.conflictingSquares.__contains__((squareSelected[0], squareSelected[1])): self.conflictingSquares.append((squareSelected[0], squareSelected[1])) if not self.conflictingSquares.__contains__((testRow, testCol)): self.conflictingSquares.append((testRow, testCol)) value = True testCol = squareSelected[1] for testRow in range(0, 9): testSquareValue = self.board[testRow][testCol] if (squareSelected[0] == testRow and squareSelected[1] == testCol): continue if( squareValue == testSquareValue ): if not self.conflictingSquares.__contains__((squareSelected[0], squareSelected[1])): self.conflictingSquares.append((squareSelected[0], squareSelected[1])) if not self.conflictingSquares.__contains__((testRow, testCol)): self.conflictingSquares.append((testRow, testCol)) value = True return value def removeDuplicates(self): for square in self.conflictingSquares[::-1]: checkQuadrant = self.checkQuadrant(square) checkLines = self.checkLines(square) if not checkQuadrant : if not checkLines : self.conflictingSquares.remove(square) def setDuplicates(self, squareSelected): self.checkQuadrant(squareSelected) self.checkLines(squareSelected)
{"/SudokuGUI.py": ["/SudokuEngine.py"]}
75,026
Abdulla-binissa/sudoku.py
refs/heads/main
/SudokuGUI.py
import pygame as pygame import SudokuEngine as SudokuEngine WIDTH = HEIGHT = 540 DIMENSION = 9 SQ_SIZE = HEIGHT // DIMENSION MAX_FPS = 15 DIGITS = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] def main(): pygame.init() pygame.font.init() font = pygame.font.Font('freesansbold.ttf', 54) screen = pygame.display.set_mode(( WIDTH, HEIGHT )) clock = pygame.time.Clock() gamestate = SudokuEngine.Gamestate() pygame.display.set_caption('Sudoku') screen.fill(pygame.Color('white')) gamestate.generateNewSudoku() squareSelected = () mainLoop = True while mainLoop: for event in pygame.event.get(): if event.type == pygame.QUIT: mainLoop = False elif event.type == pygame.MOUSEBUTTONDOWN: location = pygame.mouse.get_pos() col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE squareSelected = (row, col) elif ( event.type == pygame.KEYDOWN and gamestate.isPlayableSpot(squareSelected) ): key = event.unicode if DIGITS.__contains__(key): gamestate.setSpot(key, squareSelected) gamestate.setDuplicates(squareSelected) gamestate.removeDuplicates() drawGameState(screen, gamestate, font) clock.tick(MAX_FPS) pygame.display.flip() def drawGameState(screen, gamestate, font): drawBoard(screen) drawConflictingHighlights(screen, gamestate) drawNumbers(screen, gamestate, font) def drawBoard(screen): for r in range(DIMENSION): for c in range(DIMENSION): thickness = 1 squareOutline = pygame.Rect( c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE) squareInner = pygame.Rect( c*SQ_SIZE + thickness - thickness*(c%3), r*SQ_SIZE + thickness - thickness*(r%3), SQ_SIZE - 2*thickness, SQ_SIZE - 2*thickness) pygame.draw.rect(screen, pygame.Color("black"), squareOutline) pygame.draw.rect(screen, pygame.Color("white"), squareInner) def drawNumbers(screen, gamestate, font): for r in range(DIMENSION): for c in range(DIMENSION): square = gamestate.board[r][c] if( square != '?' ): if( gamestate.givenSquares.__contains__((r,c)) ): textsurface = font.render(square, True, (0, 0, 0)) else: textsurface = font.render(square, True, (80, 80, 80)) screen.blit(textsurface, pygame.Rect(c*SQ_SIZE + (SQ_SIZE // 4), r*SQ_SIZE + (SQ_SIZE // 8), SQ_SIZE, SQ_SIZE)) def drawConflictingHighlights(screen, gamestate): thickness = 1 s = pygame.Surface((SQ_SIZE - (2*thickness), SQ_SIZE - (2*thickness))) s.set_alpha(60) # 0 - transparent ; 255 - opaque s.fill(pygame.Color('red')) for square in gamestate.conflictingSquares: r = square[0] c = square[1] screen.blit(s, pygame.Rect( c*SQ_SIZE + thickness - thickness*(c%3), r*SQ_SIZE + thickness - thickness*(r%3), (SQ_SIZE - (2*thickness)), (SQ_SIZE - (2*thickness)))) main()
{"/SudokuGUI.py": ["/SudokuEngine.py"]}
75,029
MSC19950601/cxr_classification
refs/heads/master
/classification_cxr.py
import os import numpy as np import tensorflow as tf from Model import ChinaCXRDataset from sklearn.utils import shuffle image_width = 640 image_height = 480 pixel_depth = 255.0 # Number of levels per pixel. cxr_model = ChinaCXRDataset("CXR_png") if os.path.isfile("CXR_png_gray.pickle"): cxr_model.load_from_pickle("CXR_png_gray.pickle") else: cxr_model.load_images(image_width, image_height, pixel_depth, convert_to_gray=True) cxr_model.separate_test_dataset(200) cxr_model.save(dataset_filename="CXR_png_gray.pickle") train_dataset, train_labels = cxr_model.random_images(120) valid_dataset, valid_labels = cxr_model.random_images(120) test_dataset, test_labels = cxr_model.random_images(120, test_images=True) num_labels = 2 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_width, image_height, 1)).astype(np.float32) labels = (np.arange(num_labels) == labels[:, None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) batch_size = 16 kernel_size = 5 depth = 16 num_hidden = 64 num_channels = 1 graph1 = tf.Graph() with graph1.as_default(): # Input data. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_width, image_height, num_channels), name="input") tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels), name="labels") tf.summary.image('train_input', tf_train_dataset, 3) global_step = tf.Variable(0, trainable=False) train = tf.placeholder(tf.bool) starter_learning_rate = 0.5 learning_rate = tf.train.exponential_decay(starter_learning_rate, global_step, 500, 0.96, staircase=True) def conv(data, patch_size, num_channels, depth, name="conv"): with tf.name_scope(name): w = tf.Variable(tf.truncated_normal([patch_size, patch_size, num_channels, depth], stddev=0.1), name="W") b = tf.Variable(tf.constant(0.1, shape=[depth]), name="B") wx = tf.nn.conv2d(data, w, [1, 2, 2, 1], padding='SAME') # zero padded to keep ratio same activation = tf.nn.relu(wx + b) tf.summary.histogram("weights", w) tf.summary.histogram("biases", b) tf.summary.histogram("activation", activation) return activation def fc_layer(data, width, height, name="fc"): with tf.name_scope(name): w = tf.Variable(tf.truncated_normal([width, height], stddev=0.1), name="W") b = tf.Variable(tf.constant(0.1, shape=[height]), name="B") mul = tf.matmul(data, w) activation = tf.nn.relu(mul + b) tf.summary.histogram("weights", w) tf.summary.histogram("biases", b) tf.summary.histogram("activation", activation) return activation # Accuracy def accuracy(predictions, labels): with tf.name_scope("accuracy"): correct_prediction = tf.equal(tf.argmax(predictions, 1), tf.argmax(labels, 1)) acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar("accuracy", acc) return acc def model(data): conv1 = conv(data, kernel_size, num_channels, depth, name="conv1") conv2 = conv(conv1, kernel_size, depth, depth, name="conv2") shape = conv2.get_shape().as_list() reshape = tf.reshape(conv2, [shape[0], shape[1] * shape[2] * shape[3]], name="reshape_fc") reshape = tf.cond(train, lambda: tf.nn.dropout(reshape, keep_prob=0.7), lambda: reshape) fc1 = fc_layer(reshape, image_width // 4 * image_height // 4 * depth, num_hidden, name="fc1") fc2 = tf.cond(train, lambda: tf.nn.dropout(fc1, keep_prob=0.7), lambda: fc1) fc3 = fc_layer(fc2, num_hidden, num_labels, name="fc2") return fc3 # Training computation. logits = model(tf_train_dataset) with tf.name_scope("loss"): loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels)) tf.summary.scalar("loss", loss) # Optimizer. with tf.name_scope("optimiser"): optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # Predictions for the training, validation, and test data. train_accuracy = accuracy(logits, tf_train_labels) tf.summary.scalar("train_accuracy", train_accuracy) merged_summary = tf.summary.merge_all() # to get all var summaries in one place. def get_input_in_batch_size(batch_length, is_train=True): if is_train is False: batch_data, batch_labels = cxr_model.random_images(batch_length, test_images=True, do_shuffle=True) else: batch_data, batch_labels = cxr_model.random_images(batch_length, do_shuffle=True) return reformat(batch_data, batch_labels) num_steps = 500 def run_training(graph): with tf.Session(graph=graph) as session: tf.initialize_all_variables().run() writer = tf.summary.FileWriter('/tmp/log_simple_stats/5') writer.add_graph(session.graph) print('Initialized') for step in range(num_steps): batch_data, batch_labels = get_input_in_batch_size(batch_size, is_train=True) feed_dict = {tf_train_dataset: batch_data, tf_train_labels: batch_labels, train: True} _ = session.run([optimizer], feed_dict=feed_dict) if step % 5 == 0: batch_data, batch_labels = get_input_in_batch_size(batch_size, is_train=True) feed_dict = {tf_train_dataset: batch_data, tf_train_labels: batch_labels, train: True} valid_acc = session.run([train_accuracy], feed_dict=feed_dict) l = session.run([loss], feed_dict=feed_dict) va = session.run(merged_summary, feed_dict=feed_dict) writer.add_summary(va, step) print('Validation loss at step %d: %f' % (step, l[0])) print('Validation accuracy: %.1f%%' % (valid_acc[0]*100)) batch_data, batch_labels = get_input_in_batch_size(batch_size, is_train=False) feed_dict = {tf_train_dataset: batch_data, tf_train_labels: batch_labels, train: False} test_acc = session.run([train_accuracy], feed_dict=feed_dict) test_loss = session.run([loss], feed_dict=feed_dict) print('Test loss at step %d: %f' % (1000, test_loss[0])) print('Test accuracy: %.1f%%' % (test_acc[0] * 100)) te = session.run(merged_summary, feed_dict=feed_dict) writer.add_summary(te, 1000) print(test_acc) run_training(graph1)
{"/classification_cxr.py": ["/Model.py"]}
75,030
MSC19950601/cxr_classification
refs/heads/master
/Model.py
import os import numpy as np import matplotlib.image as mpimg from scipy import misc from six.moves import cPickle as pickle from sklearn.utils import shuffle class ChinaCXRDataset: """Dataset model to fetch images from NLM-ChinaCXRSet""" def __init__(self, folder): self._folder = folder self._image_files = os.listdir(self._folder) self._valid_images_count = 0 self._num_of_files = len(self._image_files) self._image_width = 0 self._image_height = 0 self._convert_to_gray = True self._dataset = None self._labels = None self._dataset_filename = "CXR_png.pickle" self._test_data_size = 0 self._test_dataset = None self._test_labels = None def load_images(self, image_width, image_height, pixel_depth, convert_to_gray=True): self._image_width = image_width self._image_height = image_height self._convert_to_gray = convert_to_gray if convert_to_gray is True: self._dataset = np.ndarray(shape=(self._num_of_files, image_width, image_height, 1), dtype=np.float32) else: self._dataset = np.ndarray(shape=(self._num_of_files, image_width, image_height, 3), dtype=np.float32) # RGB self._labels = np.ndarray(shape=(self._num_of_files), dtype=np.int32) num_images = 0 for image in self._image_files: try: image_file = os.path.join(self._folder, image) img = mpimg.imread(image_file) if convert_to_gray is True: img = np.dot(img[..., :3], [0.299, 0.587, 0.114]) img_scaled = misc.imresize(img, (image_width, image_height)) # Check if this creates any problems when color image is passed. image_data = (img_scaled.astype(float) - pixel_depth / 2) / pixel_depth image_data = image_data.reshape((image_width, image_height, 1 if self._convert_to_gray is True else 3)) if image_data.shape != (image_width, image_height, 1 if self._convert_to_gray is True else 3): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) self._dataset[num_images, :, :, :] = image_data # If filename ends with a 1, it means the image is a case of TB reported. if str(image_file[-5]) == "1": self._labels[num_images] = 1 else: self._labels[num_images] = 0 num_images += 1 except IOError as e: print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.') # Limits dataset to only valid images found self._valid_images_count = num_images self._dataset = self._dataset[0:num_images, :, :, :] self._labels = self._labels[0:num_images] shuffle(self._dataset, self._labels, random_state=0) print('Full dataset tensor shape :', self._dataset.shape) def load_from_pickle(self, dataset_filename="CXR_png.pickle"): if not os.path.isfile(dataset_filename): print('No file named ', dataset_filename, ' exists') return else: self._dataset_filename = dataset_filename with open(self._dataset_filename, 'rb') as f: data = pickle.load(f) self._dataset = data["dataset"] self._labels = data["labels"] self._image_height = data["height"] self._image_width = data["width"] self._valid_images_count = data["valid_images_count"] self._convert_to_gray = data["convert_to_gray"] self._folder = data["folder"] self._test_labels = data["test_labels"] self._test_data_size = data["test_data_size"] self._test_dataset = data["test_dataset"] del data def save(self, dataset_filename="CXR_png.pickle", overwrite=False): if self._dataset is None: print("Dataset is empty. Run load_images before saving.") return data = {"dataset": self._dataset, "labels": self._labels, "valid_images_count": self._valid_images_count, "width": self._image_width, "height": self._image_height, "convert_to_gray": self._convert_to_gray, "folder": self._folder, "test_dataset": self._test_dataset, "test_labels": self._test_labels, "test_data_size": self._test_data_size} if overwrite is True: if os.path.isfile(dataset_filename): os.remove(dataset_filename) try: with open(dataset_filename, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', dataset_filename, ':', e) def random_images(self, count, test_images=False, do_shuffle=False): if test_images is True and self._test_data_size == 0: print("0 images in the test dataset. Use separate_test_dataset() to load images to test dataset.") return None if self._valid_images_count == 0: print("0 images in the dataset. Use load_images or load_from_pickle to load images to dataset.") return None num = 0 dataset = np.ndarray(shape=(count, self._image_width, self._image_height, 1 if self._convert_to_gray is True else 3), dtype=np.float32) labels = np.ndarray(shape=(count), dtype=np.int32) if test_images is True: for i in np.random.randint(low=0, high=self._test_data_size, size=count): dataset[num, ...] = self._test_dataset[i, ...] labels[num] = self._test_labels[i] num += 1 else: for i in np.random.randint(low=0, high=self._valid_images_count, size=count): dataset[num, ...] = self._dataset[i, ...] labels[num] = self._labels[i] if do_shuffle is True: shuffle(dataset, labels, random_state=0) return dataset, labels def separate_test_dataset(self, num_of_test_images): if self._test_data_size != 0: print("Test files of size %s is already present in test dataset." % str(self._test_data_size)) return None if num_of_test_images >= self._valid_images_count: print("Dataset dont possess that many images.") return None if self._dataset is None: print("0 images in dataset. Add images via load_images.") return None self._test_data_size = num_of_test_images self._test_dataset = np.ndarray(shape=(num_of_test_images, self._image_width, self._image_height, 1 if self._convert_to_gray is True else 3), dtype=np.float32) self._test_labels = np.ndarray(shape=(num_of_test_images), dtype=np.int32) self._test_dataset = self._dataset[-num_of_test_images:, ...] self._test_labels = self._labels[-num_of_test_images:] self._valid_images_count -= self._test_data_size self._dataset = self._dataset[0:self._valid_images_count, :, :, :] self._labels = self._labels[0:self._valid_images_count]
{"/classification_cxr.py": ["/Model.py"]}
75,031
MSC19950601/cxr_classification
refs/heads/master
/tflearn_classify.py
from __future__ import division, print_function, absolute_import import os import numpy as np import matplotlib.image as mpimg from scipy import misc from six.moves import cPickle as pickle import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.conv import conv_2d from tflearn.layers.estimator import regression def rgb2gray(rgb): return np.dot(rgb[...,:3], [0.299, 0.587, 0.114]) # plt.imshow(gray, cmap = plt.get_cmap('gray')) # plt.show() image_width = 640 image_height = 480 pixel_depth = 255.0 # Number of levels per pixel. def load_images(folder, min_num_images): """Load the data for a single letter label.""" image_files = os.listdir(folder) dataset = np.ndarray(shape=(len(image_files), image_width, image_height), dtype=np.float32) labels = np.ndarray(shape=(len(image_files)), dtype=np.int32) print(folder) num_images = 0 for image in image_files: try: image_file = os.path.join(folder, image) img = mpimg.imread(image_file) gray = rgb2gray(img) gray_scaled = misc.imresize(gray, (image_width, image_height)) image_data = (gray_scaled.astype(float) - pixel_depth / 2) / pixel_depth if image_data.shape != (image_width, image_height): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) dataset[num_images, :, :] = image_data if str(image_file[-5]) == "1": labels[num_images] = 1 else: labels[num_images] = 0 num_images = num_images + 1 print(num_images) except IOError as e: print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.') dataset = dataset[0:num_images, :, :] labels = labels[0:num_images] if num_images < min_num_images: raise Exception('Many fewer images than expected: %d < %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset, labels def get_dataset(): set_filename = "CXR_png.pickle" if not os.path.isfile(set_filename) : dataset , labels = load_images("CXR_png",4) data = { "dataset" : dataset, "labels" : labels } try: with open(set_filename, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', set_filename, ':', e) with open(set_filename, 'rb') as f: data = pickle.load(f) dataset = data["dataset"] labels = data["labels"] # print "===LABELS===" # print labels ## remove 182 valid_dataset = np.ndarray(shape=(182, image_width, image_height), dtype=np.float32) valid_labels = np.ndarray(shape=(182), dtype=np.int32) test_dataset = np.ndarray(shape=(180, image_width, image_height), dtype=np.float32) test_labels = np.ndarray(shape=(180), dtype=np.int32) train_dataset = np.ndarray(shape=(300, image_width, image_height), dtype=np.float32) train_labels = np.ndarray(shape=(300), dtype=np.int32) ## remove 662 num_valid = 0 for i in np.random.randint(low=0, high=662, size=182): valid_dataset[num_valid,:,:] = dataset[i,:,:] valid_labels[num_valid] = labels[i] num_valid = num_valid + 1 num_test = 0 for i in np.random.randint(low=0, high=662, size=180): test_dataset[num_test,:,:] = dataset[i,:,:] test_labels[num_test] = labels[i] num_test = num_test + 1 num_train = 0 for i in np.random.randint(low=0, high=662, size=300): train_dataset[num_train,:,:] = dataset[i,:,:] train_labels[num_train] = labels[i] num_train = num_train + 1 del dataset # hint to help gc free up memory del labels del data print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) return train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels train_dataset, train_labels, valid_dataset, valid_labels, test_dataset, test_labels = get_dataset() num_labels = 2 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_width, image_height, 1)).astype(np.float32) labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) # Data loading and preprocessing # import tflearn.datasets.mnist as mnist # X, Y, testX, testY = mnist.load_data(one_hot=True) Y = train_labels testY = test_labels X = train_dataset.reshape([-1, image_width, image_height, 1]) testX = test_dataset.reshape([-1, image_width, image_height, 1]) batch_size = 16 image_width = 640 image_height = 480 num_labels = 2 filter_size = 5 depth = 16 # Building convolutional network network = input_data(shape=[None, image_width, image_height, 1], name='input') network = conv_2d(network, depth, filter_size, [1,2,2,1], activation='relu', regularizer="L2", padding='SAME') network = conv_2d(network, depth, filter_size, [1,2,2,1], activation='relu', regularizer="L2", padding='SAME') network = fully_connected(network, 64) network = dropout(network, 0.8) network = fully_connected(network, num_labels, activation='softmax') network = regression(network, optimizer='adam', learning_rate=0.001, loss='categorical_crossentropy', name='target') # Training model = tflearn.DNN(network, tensorboard_verbose=3) model.fit({'input': X}, {'target': Y}, n_epoch=20, validation_set=({'input': testX}, {'target': testY}), snapshot_step=100, show_metric=True, run_id='convnet')
{"/classification_cxr.py": ["/Model.py"]}
75,033
samuelwbock/fantasy_baseball
refs/heads/master
/predict/clean.py
import numpy as np from sklearn import preprocessing def get_file_contents(path, date): f = open(path) first = f.readline() contents = np.loadtxt(f, dtype=str, delimiter='\t') normalized = clean_data(contents, date) return normalized def floaten(data): floater = lambda x: float(x) vector = np.vectorize(floater) return vector(data) def clean_data(data: np.ndarray, date:str): labels = data[:, :2] raw_data = np.append(data[:, 3:15], data[:, 17:], 1) normalized_data = preprocessing.normalize(raw_data) dates = normalized_data[:, 0:1] normalize = lambda x: date vector = np.vectorize(normalize) dates = vector(dates) labels = np.append(dates, labels, 1) normalized = np.append(labels, normalized_data, 1) return normalized def check_columns(): master = 'Player,Team,G,AB,R,H,2B,3B,HR,RBI,SB,CS,BB,SO,HBP,AVG,OBP,SLG,OPS' first = '"Player","Team","G","PA","AB","H","2B","3B","HR","R","RBI","BB","SO","HBP","SB","CS","-1","AVG","OBP","SLG","OPS","wOBA","-1","wRC+","BsR","Fld","-1","Off","Def","WAR","-1","ADP","playerid"' second = 'Player Team Pos G AB R H 2B 3B HR RBI SB CS BB SO SH SF HBP AVG OBP SLG OPS' first = first.replace('"','').split(",") first = first[:3] + first[4:5] + first[9:10] + first[5:9] + first[10:11] + first[14:16] + first[11:14] + first[17:21] first = str.join(',', first) second = second.split(('\t')) second = second[:2] + second[3:15] + second[17:] second = str.join(',', second) assert second == first def get_predict_data(path): f = open(path) first = f.readline() contents = np.loadtxt(f, dtype=str, delimiter=',') normalize = lambda x: x.replace('"', '') vector = np.vectorize(normalize) normalized_contents = vector(contents) labels = normalized_contents[:, [0,1]] raw_data = normalized_contents[:, [2,4,9,5,6,7,8,10,14,15,11,12,13,17,18,19,20]] normalized_data = preprocessing.normalize(raw_data) normalized = np.append(labels, normalized_data, 1) return normalized def get_yearly_stats(): team_wins = np.loadtxt(open("../raw/predict/teamWins.csv"), dtype=str, delimiter=',') team_wins = team_wins[0:,[0, 3, 5]] return team_wins def get_score(players, wins): win_map = {} for win in wins: year = win[0] team = win[1] rank = win[2] if team == 'MIA': win_map[year + "FLA"] = float(rank) win_map[year + team] = float(rank) ranks = [] misses = [] scores = players[:, [0,2]] for score in scores: year = score[0] team = score[1] key = year + team if key not in win_map: misses.append(key) else: ranks.append(win_map[key]) return np.array(ranks) def get_data(): training_data = None for i in range(0,9): file_contents = get_file_contents("../raw/predict/201{}.csv".format(i), '201{}'.format(i)) if training_data is None: training_data = file_contents else: training_data = np.append(training_data, file_contents, 0) predict_data = get_predict_data("../raw/test/predict.csv") yearly_stats = get_yearly_stats() scores = get_score(training_data, yearly_stats) labels = predict_data[:, 0:2] predict_data = floaten(predict_data[:, 2:]) training_data = floaten(training_data[:, 3:]) return training_data, labels, predict_data, scores check_columns() get_data()
{"/predict/train.py": ["/predict/clean.py"]}
75,034
samuelwbock/fantasy_baseball
refs/heads/master
/predict/train.py
from sklearn.neural_network import MLPRegressor import numpy as np from predict.clean import get_data, get_yearly_stats def sort_predictions(labeled_preds): results = [] for labeled_pred in labeled_preds: key = '{}__{}'.format(str(labeled_pred[2]), labeled_pred[0]) results.append(key) results.sort() return results def main(): training_data, labels, predict_data, scores = get_data() clr = MLPRegressor(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) fit = clr.fit(training_data, scores) pred = fit.predict(predict_data) labeled_preds = np.append(labels, np.reshape(pred, [4112,1]), 1) sorted = sort_predictions(labeled_preds) f = open('pitchers.txt', 'w') for rec in sorted: f.write(rec + '\n') f.close() if __name__ == "__main__": main()
{"/predict/train.py": ["/predict/clean.py"]}
75,037
alalawy/regius-app
refs/heads/master
/routes/routes.py
from routes import regius from controller import controller regius.add_link('/', controller.Index) regius.add_link('/halo/{name}', controller.Name) regius.add_link('/redirect', controller.SampleRedirect)
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,038
alalawy/regius-app
refs/heads/master
/app.py
from routes import regius, routes app = regius app.serve("0.0.0.0","8011")
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,039
alalawy/regius-app
refs/heads/master
/controller/controller.py
from controller import regius from regius import * from database.models import * class Index: def get(self, req, resp): data = {"welcome": "Welcome, Your Web Successfully Running !"} resp.text = regius.template("index.html", data=data) class Name: def get(self, req, resp, nama): resp.text = "Hello " + nama class SampleRedirect: def get(self, req, resp): regius.redirect(req, resp, "/halo/Jhon")
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,040
alalawy/regius-app
refs/heads/master
/database/models.py
from regius import * from database.core import Db #==========================# # MODELS # #==========================# class DataNama(Db.Base): __tablename__ = "data_nama" id = Column(Integer, primary_key=True) nama = Column(String(45)) alamat = Column(String(45)) status = Column(Integer)
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,041
alalawy/regius-app
refs/heads/master
/database/core.py
from regius import * from database.config import * class Db: if db == "mysql": enginedb = create_engine('mysql+pymysql://' + user + ':' + password + '@' + server + '/' + db_name) if db == "postgresql": enginedb = create_engine('postgresql://' + user + ':' + password + '@' + server + '/' + db_name) Session = sessionmaker(bind=enginedb) session = Session() Base = declarative_base() def save(models): Db.session.add(models) Db.session.commit() def show_all(models): data = Db.session.query(models).all() return data show = session
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,042
alalawy/regius-app
refs/heads/master
/database/config.py
#==========================# # CONFIGDB # #==========================# db = "mysql" server = "localhost" user = "root" password = "14091996Aa" db_name = "cobaregius"
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,043
alalawy/regius-app
refs/heads/master
/routes/__init__.py
from regius import Regius regius = Regius()
{"/routes/routes.py": ["/routes/__init__.py"], "/app.py": ["/routes/__init__.py"], "/controller/controller.py": ["/database/models.py"], "/database/models.py": ["/database/core.py"], "/database/core.py": ["/database/config.py"]}
75,046
codeway3/tickets_tool
refs/heads/master
/res/parse_station.py
""" 用于从12306的车站信息列表更新生成本地的车站信息文件 TODO 在12306更新过数据格式后 该模块需要重写 """ import re import requests from pprint import pprint url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.8963' r = requests.get(url, verify=False) stations = re.findall(r'([A-Z]+)\|([a-z]+)', r.text) stations = dict(stations) stations = dict(zip(stations.values(), stations.keys())) pprint(stations, indent=4)
{"/tickets.py": ["/train.py", "/utils.py"], "/utils.py": ["/res/stations.py"]}
75,047
codeway3/tickets_tool
refs/heads/master
/res/stations.py
stations = { 'acheng': 'ACB', 'aershan': 'ART', 'aershanbei': 'ARX', 'aihe': 'AHP', 'aijiacun': 'AJJ', 'ajin': 'AJD', 'akesu': 'ASR', 'aketao': 'AER', 'alashankou': 'AKR', 'alihe': 'AHX', 'alongshan': 'ASX', 'amuer': 'JTX', 'ananzhuang': 'AZM', 'anda': 'ADX', 'ande': 'ARW', 'anding': 'ADP', 'angangxi': 'AAX', 'anguang': 'AGT', 'anhua': 'PKQ', 'anjia': 'AJB', 'ankang': 'AKY', 'ankouyao': 'AYY', 'anlong': 'AUZ', 'anlu': 'ALN', 'anping': 'APT', 'anqing': 'AQH', 'anqingxi': 'APH', 'anren': 'ARG', 'anshan': 'AST', 'anshanxi': 'AXT', 'anshun': 'ASW', 'anshunxi': 'ASE', 'antang': 'ATV', 'antingbei': 'ASH', 'antu': 'ATL', 'antuxi': 'AXL', 'anxi': 'AXS', 'anyang': 'AYF', 'anyangdong': 'ADF', 'aojiang': 'ARH', 'aolibugao': 'ALD', 'atushi': 'ATR', 'babu': 'BBE', 'bachu': 'BCR', 'badaling': 'ILP', 'badong': 'BNN', 'baibiguan': 'BGV', 'baicheng': 'BCT', 'baigou': 'FEP', 'baiguo': 'BGM', 'baihe': 'BEL', 'baihedong': 'BIY', 'baihexian': 'BEY', 'baijian': 'BAP', 'baijigou': 'BJJ', 'baijipo': 'BBM', 'baikuipu': 'BKB', 'bailang': 'BAT', 'bailixia': 'AAP', 'baimajing': 'BFQ', 'baiqi': 'BQP', 'baiquan': 'BQL', 'baise': 'BIZ', 'baisha': 'BSW', 'baishanshi': 'HJL', 'baishapo': 'BPM', 'baishishan': 'BAL', 'baishuijiang': 'BSY', 'baishuixian': 'BGY', 'baishuizhen': 'BUM', 'baiyangdian': 'FWP', 'baiyi': 'FHW', 'baiyinchagan': 'BYC', 'baiyinhuanan': 'FNC', 'baiyinhushuo': 'BCD', 'baiyinshi': 'BNJ', 'baiyintala': 'BID', 'baiyinxi': 'BXJ', 'baiyunebo': 'BEC', 'bajiaotai': 'BTD', 'balin': 'BLX', 'bamiancheng': 'BMD', 'bamiantong': 'BMB', 'bancheng': 'BUP', 'banmaoqing': 'BNM', 'bantian': 'BTQ', 'baodi': 'BPP', 'baoding': 'BDP', 'baodingdong': 'BMP', 'baohuashan': 'BWH', 'baoji': 'BJY', 'baojinan': 'BBY', 'baokang': 'BKD', 'baolage': 'BQC', 'baolin': 'BNB', 'baolongshan': 'BND', 'baoqing': 'BUB', 'baoquanling': 'BQB', 'baotou': 'BTC', 'baotoudong': 'BDC', 'bashan': 'BAY', 'baxiantong': 'VXD', 'bayangaole': 'BAC', 'bayuquan': 'BYT', 'bazhong': 'IEW', 'bazhongdong': 'BDE', 'bazhou': 'RMP', 'bazhouxi': 'FOP', 'beian': 'BAB', 'beibei': 'BPW', 'beidaihe': 'BEP', 'beihai': 'BHZ', 'beijiao': 'IBQ', 'beijing': 'BJP', 'beijingbei': 'VAP', 'beijingdong': 'BOP', 'beijingnan': 'VNP', 'beijingxi': 'BXP', 'beijingzi': 'BRT', 'beiliu': 'BOZ', 'beimaquanzi': 'BRP', 'beipiaonan': 'RPD', 'beitai': 'BTT', 'beitun': 'BYP', 'beitunshi': 'BXR', 'beiying': 'BIV', 'beiyinhe': 'BYB', 'beizhai': 'BVP', 'bencha': 'FWH', 'bengbu': 'BBH', 'bengbunan': 'BMH', 'benhong': 'BVC', 'benxi': 'BXT', 'benxihu': 'BHT', 'benxixincheng': 'BVT', 'bijiang': 'BLQ', 'bijiashan': 'BSB', 'bijiguan': 'BJM', 'binhai': 'FHP', 'binhaibei': 'FCP', 'binjiang': 'BJB', 'binxian': 'BXY', 'binyang': 'UKZ', 'binzhou': 'BIK', 'bishan': 'FZW', 'boao': 'BWQ', 'bobai': 'BBZ', 'boketu': 'BKX', 'bole': 'BOR', 'boli': 'BLB', 'botou': 'BZP', 'boxing': 'BXK', 'bozhou': 'BZH', 'buhai': 'BUT', 'buliekai': 'BLR', 'caijiagou': 'CJT', 'caijiapo': 'CJY', 'caishan': 'CON', 'cangnan': 'CEH', 'cangshi': 'CST', 'cangxi': 'CXE', 'cangzhou': 'COP', 'cangzhouxi': 'CBP', 'caohai': 'WBW', 'caohekou': 'CKT', 'caoshi': 'CSL', 'caoxian': 'CXK', 'caozili': 'CFP', 'ceheng': 'CHZ', 'cenxi': 'CNZ', 'chabuga': 'CBC', 'chaigang': 'CGT', 'chaigoupu': 'CGV', 'chaihe': 'CHB', 'chajiang': 'CAM', 'chaka': 'CVO', 'chaling': 'CDG', 'chalingnan': 'CNG', 'changcheng': 'CEJ', 'changchong': 'CCM', 'changchun': 'CCT', 'changchunnan': 'CET', 'changchunxi': 'CRT', 'changde': 'VGQ', 'changdian': 'CDT', 'changge': 'CEF', 'changle': 'CLK', 'changli': 'CLP', 'changlingzi': 'CLT', 'changlinhe': 'FVH', 'changnong': 'CNJ', 'changping': 'DAQ', 'changpingbei': 'VBP', 'changpingdong': 'FQQ', 'changpoling': 'CPM', 'changqingqiao': 'CQJ', 'changsha': 'CSQ', 'changshanan': 'CWQ', 'changshantun': 'CVT', 'changshou': 'EFW', 'changshoubei': 'COW', 'changshouhu': 'CSE', 'changting': 'CES', 'changtingnan': 'CNS', 'changtingzhen': 'CDB', 'changtu': 'CTT', 'changtuxi': 'CPT', 'changwu': 'CWY', 'changxing': 'CBH', 'changxingnan': 'CFH', 'changyang': 'CYN', 'changyuan': 'CYF', 'changzheng': 'CZJ', 'changzhi': 'CZF', 'changzhibei': 'CBF', 'changzhou': 'CZH', 'changzhoubei': 'ESH', 'changzhuang': 'CVK', 'chaohu': 'CIH', 'chaohudong': 'GUH', 'chaolianggou': 'CYP', 'chaoshan': 'CBQ', 'chaoyang': 'CYD', 'chaoyangchuan': 'CYL', 'chaoyangdi': 'CDD', 'chaoyangzhen': 'CZL', 'chaozhou': 'CKQ', 'chasuqi': 'CSC', 'chengcheng': 'CUY', 'chengde': 'CDP', 'chengdedong': 'CCP', 'chengdu': 'CDW', 'chengdudong': 'ICW', 'chengdunan': 'CNW', 'chenggaozi': 'CZB', 'chenggu': 'CGY', 'chengjisihan': 'CJX', 'chenguanying': 'CAJ', 'chengyang': 'CEK', 'chengzitan': 'CWT', 'chenming': 'CMB', 'chenqing': 'CQB', 'chenxi': 'CXQ', 'chenxiangtun': 'CXT', 'chenzhou': 'CZQ', 'chenzhouxi': 'ICQ', 'chezhuanwan': 'CWM', 'chibi': 'CBN', 'chibibei': 'CIN', 'chifeng': 'CFD', 'chifengxi': 'CID', 'chizhou': 'IYH', 'chongqing': 'CQW', 'chongqingbei': 'CUW', 'chongqingnan': 'CRW', 'chongren': 'CRG', 'chongzuo': 'CZZ', 'chuangyecun': 'CEX', 'chunwan': 'CQQ', 'chunyang': 'CAL', 'chushan': 'CSB', 'chuxiong': 'COM', 'chuzhou': 'CXH', 'chuzhoubei': 'CUH', 'cili': 'CUQ', 'cishan': 'CSP', 'cixi': 'CRP', 'cixian': 'CIP', 'ciyao': 'CYK', 'congjiang': 'KNW', 'cuihuangkou': 'CHP', 'cuogang': 'CAX', 'daan': 'RAT', 'daanbei': 'RNT', 'daba': 'DBJ', 'daban': 'DBC', 'dachaigou': 'DGJ', 'dacheng': 'DCT', 'dadenggou': 'DKJ', 'dafangnan': 'DNE', 'daguan': 'RGW', 'daguantun': 'DTT', 'dagushan': 'RMT', 'dahongqi': 'DQD', 'dahuichang': 'DHP', 'dahushan': 'DHD', 'dailing': 'DLB', 'daixian': 'DKV', 'daiyue': 'RYV', 'dajiagou': 'DJT', 'dajian': 'DFP', 'daju': 'DIM', 'dakoutun': 'DKP', 'dalateqi': 'DIC', 'dalatexi': 'DNC', 'dali': 'DNY', 'dalian': 'DLT', 'dalianbei': 'DFT', 'dalin': 'DLD', 'daluhao': 'DLC', 'dandong': 'DUT', 'dandongxi': 'RWT', 'danfeng': 'DGY', 'dangshan': 'DKH', 'dangshannan': 'PRH', 'dangtudong': 'OWH', 'dangyang': 'DYN', 'dani': 'DNZ', 'dantu': 'RUH', 'danxiashan': 'IRQ', 'danyang': 'DYH', 'danyangbei': 'EXH', 'daobao': 'RBT', 'daoerdeng': 'DRD', 'daoqing': 'DML', 'daozhou': 'DFZ', 'dapanshi': 'RPP', 'dapingfang': 'DPD', 'dapu': 'DVT', 'daqilaha': 'DQX', 'daqing': 'DZX', 'daqingdong': 'LFX', 'daqinggou': 'DSD', 'daqingxi': 'RHX', 'dashiqiao': 'DQT', 'dashitou': 'DSL', 'dashitounan': 'DAL', 'dashizhai': 'RZT', 'datianbian': 'DBM', 'datong': 'DTV', 'datongxi': 'DTO', 'datun': 'DNT', 'dawang': 'WWQ', 'dawangtan': 'DZZ', 'dawanzi': 'DFM', 'dawukou': 'DFJ', 'daxing': 'DXX', 'daxinggou': 'DXL', 'dayan': 'DYX', 'dayangshu': 'DUX', 'dayebei': 'DBN', 'daying': 'DYV', 'dayingdong': 'IAW', 'dayingzhen': 'DJP', 'dayingzi': 'DZD', 'dayu': 'DYG', 'dayuan': 'DYZ', 'dazhanchang': 'DTJ', 'dazhangzi': 'DAP', 'dazhou': 'RXW', 'dazhuyuan': 'DZY', 'dazunan': 'FQW', 'dean': 'DAG', 'debao': 'RBZ', 'debosi': 'RDT', 'dechang': 'DVW', 'deerbuer': 'DRX', 'dehui': 'DHT', 'dehuixi': 'DXT', 'delingha': 'DHO', 'dengshahe': 'DWT', 'dengta': 'DGT', 'dengzhou': 'DOF', 'deqing': 'DRH', 'deqingxi': 'MOH', 'dexing': 'DWG', 'deyang': 'DYW', 'dezhou': 'DZP', 'dezhoudong': 'DIP', 'dianjiang': 'DJE', 'dianxin': 'DXM', 'didao': 'DDB', 'dingbian': 'DYJ', 'dinghudong': 'UWQ', 'dinghushan': 'NVQ', 'dingnan': 'DNG', 'dingtao': 'DQK', 'dingxi': 'DSJ', 'dingxiang': 'DXV', 'dingyuan': 'EWH', 'dingzhou': 'DXP', 'dingzhoudong': 'DOP', 'diwopu': 'DWJ', 'dizhuang': 'DVQ', 'dongandong': 'DCZ', 'dongbianjing': 'DBB', 'dongdaihe': 'RDD', 'dongerdaohe': 'DRB', 'dongfang': 'UFQ', 'dongfanghong': 'DFB', 'dongfeng': 'DIL', 'donggangbei': 'RGT', 'dongguan': 'RTQ', 'dongguandong': 'DMQ', 'dongguang': 'DGP', 'donghai': 'DHB', 'donghaixian': 'DQH', 'dongjin': 'DKB', 'dongjingcheng': 'DJB', 'donglai': 'RVD', 'dongmiaohe': 'DEP', 'dongmingcun': 'DMD', 'dongmingxian': 'DNF', 'dongsheng': 'DRQ', 'dongshengxi': 'DYC', 'dongtai': 'DBH', 'dongtonghua': 'DTL', 'dongwan': 'DRJ', 'dongxiang': 'DXG', 'dongxinzhuang': 'DXD', 'dongxu': 'RXP', 'dongying': 'DPK', 'dongyingnan': 'DOK', 'dongyudi': 'DBV', 'dongzhen': 'DNV', 'dongzhi': 'DCH', 'dongzhuang': 'DZV', 'douluo': 'DLV', 'douzhangzhuang': 'RZP', 'douzhuang': 'ROP', 'duanzhou': 'WZQ', 'duge': 'DMM', 'duiqingshan': 'DQB', 'duizhen': 'DWV', 'dujia': 'DJL', 'dujiangyan': 'DDW', 'dulitun': 'DTX', 'dunhua': 'DHL', 'dunhuang': 'DHJ', 'dushan': 'RWW', 'dushupu': 'DPM', 'duyun': 'RYW', 'duyundong': 'KJW', 'ebian': 'EBW', 'eerduosi': 'EEC', 'ejina': 'EJC', 'emei': 'EMW', 'emeishan': 'IXW', 'enshi': 'ESN', 'erdaogoumen': 'RDP', 'erdaowan': 'RDX', 'erlian': 'RLC', 'erlong': 'RLD', 'erlongshantun': 'ELA', 'ermihe': 'RML', 'erying': 'RYJ', 'ezhou': 'ECN', 'ezhoudong': 'EFN', 'faer': 'FEM', 'fanchangxi': 'PUH', 'fangchenggangbei': 'FBZ', 'fanjiatun': 'FTT', 'fanshi': 'FSV', 'fanzhen': 'VZK', 'faqi': 'FQE', 'feidong': 'FIH', 'feixian': 'FXK', 'fengcheng': 'FCG', 'fengchengdong': 'FDT', 'fengchengnan': 'FNG', 'fengdu': 'FUW', 'fenghua': 'FHH', 'fenghuangcheng': 'FHT', 'fenghuangjichang': 'FJQ', 'fenglezhen': 'FZB', 'fenglingdu': 'FLV', 'fengshuicun': 'FSJ', 'fengshun': 'FUQ', 'fengtun': 'FTX', 'fengxian': 'FXY', 'fengyang': 'FUH', 'fengzhen': 'FZC', 'fengzhou': 'FZY', 'fenhe': 'FEV', 'fenyang': 'FAV', 'fenyi': 'FYG', 'foshan': 'FSQ', 'fuan': 'FAS', 'fuchuan': 'FDZ', 'fuding': 'FES', 'fuhai': 'FHX', 'fujin': 'FIB', 'fulaerji': 'FRX', 'fuling': 'FLW', 'fulingbei': 'FEW', 'fuliqu': 'FLJ', 'fulitun': 'FTB', 'funan': 'FNH', 'funing': 'FNP', 'fuqing': 'FQS', 'fuquan': 'VMW', 'fushankou': 'FKP', 'fushanzhen': 'FZQ', 'fushun': 'FST', 'fushunbei': 'FET', 'fusong': 'FSL', 'fusui': 'FSZ', 'futian': 'NZQ', 'futuyu': 'FYP', 'fuxian': 'FEY', 'fuxiandong': 'FDY', 'fuxin': 'FXD', 'fuyang': 'FYH', 'fuyu': 'FYT', 'fuyuan': 'FYB', 'fuyubei': 'FBT', 'fuzhou': 'FZS', 'fuzhoubei': 'FBG', 'fuzhoudong': 'FDG', 'fuzhounan': 'FYS', 'gaizhou': 'GXT', 'gaizhouxi': 'GAT', 'gancaodian': 'GDJ', 'gangou': 'GGL', 'gangu': 'GGJ', 'ganhe': 'GAX', 'ganluo': 'VOW', 'ganqika': 'GQD', 'ganquan': 'GQY', 'ganquanbei': 'GEY', 'ganshui': 'GSW', 'gantang': 'GNJ', 'ganzhou': 'GZG', 'gaoan': 'GCG', 'gaobeidian': 'GBP', 'gaobeidiandong': 'GMP', 'gaocheng': 'GEP', 'gaocun': 'GCV', 'gaogezhuang': 'GGP', 'gaolan': 'GEJ', 'gaoloufang': 'GFM', 'gaomi': 'GMK', 'gaoping': 'GPF', 'gaoqiaozhen': 'GZD', 'gaoshanzi': 'GSD', 'gaotai': 'GTJ', 'gaotainan': 'GAJ', 'gaotan': 'GAY', 'gaoyi': 'GIP', 'gaoyixi': 'GNP', 'gaozhou': 'GSQ', 'gashidianzi': 'GXD', 'gediannan': 'GNN', 'geermu': 'GRO', 'gegenmiao': 'GGT', 'geju': 'GEM', 'genhe': 'GEX', 'gezhenpu': 'GZT', 'gongcheng': 'GCZ', 'gongmiaozi': 'GMC', 'gongnonghu': 'GRT', 'gongpengzi': 'GPT', 'gongqingcheng': 'GAG', 'gongyi': 'GXF', 'gongyinan': 'GYF', 'gongyingzi': 'GYD', 'gongzhuling': 'GLT', 'gongzhulingnan': 'GBT', 'goubangzi': 'GBD', 'guan': 'GFP', 'guangan': 'VJW', 'guangannan': 'VUW', 'guangao': 'GVP', 'guangde': 'GRH', 'guanghan': 'GHW', 'guanghanbei': 'GVW', 'guangmingcheng': 'IMQ', 'guangnanwei': 'GNM', 'guangning': 'FBQ', 'guangningsi': 'GQT', 'guangningsinan': 'GNT', 'guangshan': 'GUN', 'guangshui': 'GSN', 'guangtongbei': 'GPM', 'guangyuan': 'GYW', 'guangyuannan': 'GAW', 'guangze': 'GZS', 'guangzhou': 'GZQ', 'guangzhoubei': 'GBQ', 'guangzhoudong': 'GGQ', 'guangzhounan': 'IZQ', 'guangzhouxi': 'GXQ', 'guanlin': 'GLF', 'guanling': 'GLE', 'guanshui': 'GST', 'guanting': 'GTP', 'guantingxi': 'KEP', 'guanzhaishan': 'GSS', 'guanzijing': 'GOT', 'guazhou': 'GZJ', 'gucheng': 'GCN', 'guchengzhen': 'GZB', 'gudong': 'GDV', 'guian': 'GAE', 'guiding': 'GTW', 'guidingbei': 'FMW', 'guidingnan': 'IDW', 'guidingxian': 'KIW', 'guigang': 'GGZ', 'guilin': 'GLZ', 'guilinbei': 'GBZ', 'guilinxi': 'GEZ', 'guiliuhe': 'GHT', 'guiping': 'GAZ', 'guixi': 'GXG', 'guiyang': 'GIW', 'guiyangbei': 'KQW', 'gujiao': 'GJV', 'gujiazi': 'GKT', 'gulang': 'GLJ', 'gulian': 'GRX', 'guojiadian': 'GDT', 'guoleizhuang': 'GLP', 'guosong': 'GSL', 'guoyang': 'GYH', 'guozhen': 'GZY', 'gushankou': 'GSP', 'gushi': 'GXN', 'gutian': 'GTS', 'gutianbei': 'GBS', 'gutianhuizhi': 'STS', 'guyuan': 'GUJ', 'guzhen': 'GEH', 'haerbin': 'HBB', 'haerbinbei': 'HTB', 'haerbindong': 'VBB', 'haerbinxi': 'VAB', 'haianxian': 'HIH', 'haibei': 'HEB', 'haicheng': 'HCT', 'haichengxi': 'HXT', 'haidongxi': 'HDO', 'haikou': 'VUQ', 'haikoudong': 'HMQ', 'hailaer': 'HRX', 'hailin': 'HRB', 'hailong': 'HIL', 'hailun': 'HLB', 'haining': 'HNH', 'hainingxi': 'EUH', 'haishiwan': 'HSO', 'haituozi': 'HZT', 'haiwan': 'RWH', 'haiyang': 'HYK', 'haiyangbei': 'HEK', 'halahai': 'HIT', 'halasu': 'HAX', 'hami': 'HMR', 'hancheng': 'HCY', 'hanchuan': 'HCN', 'hanconggou': 'HKB', 'handan': 'HDP', 'handandong': 'HPP', 'hanfuwan': 'HXJ', 'hangjinhouqi': 'HDC', 'hangu': 'HGP', 'hangzhou': 'HZH', 'hangzhoudong': 'HGH', 'hangzhounan': 'XHH', 'hanjiang': 'HJS', 'hankou': 'HKN', 'hanling': 'HAT', 'hanmaying': 'HYP', 'hanshou': 'VSQ', 'hanyin': 'HQY', 'hanyuan': 'WHW', 'hanzhong': 'HOY', 'haolianghe': 'HHB', 'hebei': 'HMB', 'hebi': 'HAF', 'hebian': 'HBV', 'hebidong': 'HFF', 'hechuan': 'WKW', 'hechun': 'HCZ', 'hefei': 'HFH', 'hefeibeicheng': 'COH', 'hefeinan': 'ENH', 'hefeixi': 'HTH', 'hegang': 'HGB', 'heichongtan': 'HCJ', 'heihe': 'HJB', 'heijing': 'HIM', 'heishui': 'HOT', 'heitai': 'HQB', 'heiwang': 'HWK', 'hejiadian': 'HJJ', 'hejianxi': 'HXP', 'hejin': 'HJV', 'hejing': 'HJR', 'hekoubei': 'HBM', 'hekounan': 'HKJ', 'heli': 'HOB', 'helong': 'HLL', 'hengdaohezi': 'HDB', 'hengfeng': 'HFG', 'henggouqiaodong': 'HNN', 'hengnan': 'HNG', 'hengshan': 'HSQ', 'hengshanxi': 'HEQ', 'hengshui': 'HSP', 'hengyang': 'HYQ', 'hengyangdong': 'HVQ', 'heping': 'VAQ', 'hepu': 'HVZ', 'heqing': 'HQM', 'heshengqiaodong': 'HLN', 'heshituoluogai': 'VSR', 'heshuo': 'VUR', 'hetian': 'VTR', 'heyang': 'HAY', 'heyangbei': 'HTY', 'heyuan': 'VIQ', 'heze': 'HIK', 'hezhou': 'HXZ', 'hongan': 'HWN', 'honganxi': 'VXN', 'hongguangzhen': 'IGW', 'hongguo': 'HEM', 'honghe': 'HPB', 'honghuagou': 'VHD', 'hongjiang': 'HFM', 'hongqing': 'HEY', 'hongshan': 'VSB', 'hongshaxian': 'VSJ', 'hongsipu': 'HSJ', 'hongtong': 'HDV', 'hongtongxi': 'HTV', 'hongxiantai': 'HTJ', 'hongxing': 'VXB', 'hongxinglong': 'VHB', 'hongyan': 'VIX', 'houma': 'HMV', 'houmaxi': 'HPV', 'houmen': 'KMQ', 'huacheng': 'VCQ', 'huade': 'HGC', 'huahu': 'KHN', 'huaian': 'AUH', 'huaiannan': 'AMH', 'huaibei': 'HRH', 'huaibin': 'HVN', 'huaihua': 'HHQ', 'huaihuanan': 'KAQ', 'huaiji': 'FAQ', 'huainan': 'HAH', 'huainandong': 'HOH', 'huairen': 'HRV', 'huairendong': 'HFV', 'huairou': 'HRP', 'huairoubei': 'HBP', 'huajia': 'HJT', 'huajiazhuang': 'HJM', 'hualin': 'HIB', 'huanan': 'HNB', 'huangbai': 'HBL', 'huangchuan': 'KCN', 'huangcun': 'HCP', 'huanggang': 'KGN', 'huanggangdong': 'KAN', 'huanggangxi': 'KXN', 'huangguayuan': 'HYM', 'huanggutun': 'HTT', 'huanghejingqu': 'HCF', 'huanghuatong': 'HUD', 'huangkou': 'KOH', 'huangling': 'ULY', 'huanglingnan': 'VLY', 'huangliu': 'KLQ', 'huangmei': 'VEH', 'huangnihe': 'HHL', 'huangshan': 'HKH', 'huangshanbei': 'NYH', 'huangshi': 'HSN', 'huangshibei': 'KSN', 'huangshidong': 'OSN', 'huangsongdian': 'HDL', 'huangyangtan': 'HGJ', 'huangyangzhen': 'HYJ', 'huangyuan': 'HNO', 'huangzhou': 'VON', 'huantai': 'VTK', 'huanxintian': 'VTB', 'huapengzi': 'HZM', 'huaqiao': 'VQH', 'huarong': 'HRN', 'huarongdong': 'HPN', 'huarongnan': 'KRN', 'huashan': 'HSY', 'huashanbei': 'HDY', 'huashannan': 'KNN', 'huaying': 'HUW', 'huayuan': 'HUN', 'huayuankou': 'HYT', 'huazhou': 'HZZ', 'huhehaote': 'HHC', 'huhehaotedong': 'NDC', 'huian': 'HNS', 'huichangbei': 'XEG', 'huidong': 'KDQ', 'huihuan': 'KHQ', 'huinong': 'HMJ', 'huishan': 'VCH', 'huitong': 'VTQ', 'huixian': 'HYY', 'huizhou': 'HCQ', 'huizhounan': 'KNQ', 'huizhouxi': 'VXQ', 'hukou': 'HKG', 'hulan': 'HUB', 'hulin': 'VLB', 'huludao': 'HLD', 'huludaobei': 'HPD', 'hulusitai': 'VTJ', 'humen': 'IUQ', 'hunchun': 'HUL', 'hunhe': 'HHT', 'huoerguosi': 'HFR', 'huojia': 'HJF', 'huolianzhai': 'HLT', 'huolinguole': 'HWD', 'huoqiu': 'FBH', 'huozhou': 'HZV', 'huozhoudong': 'HWV', 'hushiha': 'HHP', 'hushitai': 'HUT', 'huzhou': 'VZH', 'jiafeng': 'JFF', 'jiagedaqi': 'JGX', 'jialuhe': 'JLF', 'jiamusi': 'JMB', 'jian': 'VAG', 'jianchang': 'JFD', 'jianfeng': 'PFQ', 'jiangbiancun': 'JBG', 'jiangdu': 'UDH', 'jianghua': 'JHZ', 'jiangjia': 'JJB', 'jiangjin': 'JJW', 'jiangle': 'JLS', 'jiangmen': 'JWQ', 'jiangning': 'JJH', 'jiangningxi': 'OKH', 'jiangqiao': 'JQX', 'jiangshan': 'JUH', 'jiangsuotian': 'JOM', 'jiangyan': 'UEH', 'jiangyong': 'JYZ', 'jiangyou': 'JFW', 'jiangyuan': 'SZL', 'jianhu': 'AJH', 'jianningxianbei': 'JCS', 'jianou': 'JVS', 'jianouxi': 'JUS', 'jiansanjiang': 'JIB', 'jianshe': 'JET', 'jianshi': 'JRN', 'jianshui': 'JSM', 'jianyang': 'JYS', 'jianyangnan': 'JOW', 'jiaocheng': 'JNV', 'jiaohe': 'JHL', 'jiaohexi': 'JOL', 'jiaomei': 'JES', 'jiaozhou': 'JXK', 'jiaozhoubei': 'JZK', 'jiaozuo': 'JOF', 'jiaozuodong': 'WEF', 'jiashan': 'JOP', 'jiashannan': 'EAH', 'jiaxiang': 'JUK', 'jiaxing': 'JXH', 'jiaxingnan': 'EPH', 'jiaxinzi': 'JXT', 'jiayuguan': 'JGJ', 'jiayuguannan': 'JBJ', 'jidong': 'JOB', 'jieshoushi': 'JUN', 'jiexiu': 'JXV', 'jiexiudong': 'JDV', 'jieyang': 'JRQ', 'jiguanshan': 'JST', 'jijiagou': 'VJD', 'jilin': 'JLL', 'jiling': 'JLJ', 'jimobei': 'JVK', 'jinan': 'JNK', 'jinandong': 'JAK', 'jinanxi': 'JGK', 'jinbaotun': 'JBD', 'jinchang': 'JCJ', 'jincheng': 'JCF', 'jinchengbei': 'JEF', 'jinchengjiang': 'JJZ', 'jingbian': 'JIY', 'jingchuan': 'JAJ', 'jingde': 'NSH', 'jingdezhen': 'JCG', 'jingdian': 'JFP', 'jinggangshan': 'JGG', 'jinghai': 'JHP', 'jinghe': 'JHR', 'jinghenan': 'JIR', 'jingmen': 'JMN', 'jingnan': 'JNP', 'jingoutun': 'VGP', 'jingpeng': 'JPC', 'jingshan': 'JCN', 'jingtai': 'JTJ', 'jingtieshan': 'JVJ', 'jingxi': 'JMZ', 'jingxian': 'LOH', 'jingxing': 'JJP', 'jingyu': 'JYL', 'jingyuan': 'JYJ', 'jingyuanxi': 'JXJ', 'jingzhou': 'JBN', 'jinhe': 'JHX', 'jinhua': 'JBH', 'jinhuanan': 'RNH', 'jining': 'JIK', 'jiningnan': 'JAC', 'jinjiang': 'JJS', 'jinkeng': 'JKT', 'jinmacun': 'JMM', 'jinshanbei': 'EGH', 'jinshantun': 'JTB', 'jinxian': 'JUG', 'jinxiannan': 'JXG', 'jinyuewan': 'PYQ', 'jinyun': 'JYH', 'jinyunxi': 'PYH', 'jinzhai': 'JZH', 'jinzhangzi': 'JYD', 'jinzhong': 'JZV', 'jinzhou': 'JZT', 'jinzhounan': 'JOD', 'jishan': 'JVV', 'jishou': 'JIQ', 'jishu': 'JSL', 'jiujiang': 'JJG', 'jiuquan': 'JQJ', 'jiuquannan': 'JNJ', 'jiusan': 'SSX', 'jiutai': 'JTL', 'jiutainan': 'JNL', 'jiuzhuangwo': 'JVP', 'jiwen': 'JWX', 'jixi': 'JXB', 'jixian': 'JKP', 'jixibei': 'NRH', 'jixixian': 'JRH', 'jiyuan': 'JYF', 'juancheng': 'JCK', 'jubao': 'JRT', 'junan': 'JOK', 'junde': 'JDB', 'junliangchengbei': 'JMP', 'jurongxi': 'JWH', 'juxian': 'JKK', 'juye': 'JYK', 'kaian': 'KAT', 'kaifeng': 'KFF', 'kaifengbei': 'KBF', 'kaijiang': 'KAW', 'kaili': 'KLW', 'kailinan': 'QKW', 'kailu': 'KLC', 'kaitong': 'KTT', 'kaiyang': 'KVW', 'kaiyuan': 'KYT', 'kaiyuanxi': 'KXT', 'kalaqi': 'KQX', 'kangcheng': 'KCP', 'kangjinjing': 'KJB', 'kangxiling': 'KXZ', 'kangzhuang': 'KZP', 'kashi': 'KSR', 'kedong': 'KOB', 'kelamayi': 'KHR', 'kelan': 'KLV', 'keshan': 'KSB', 'keyihe': 'KHX', 'kouqian': 'KQL', 'kuandian': 'KDT', 'kuche': 'KCR', 'kuduer': 'KDX', 'kuerle': 'KLR', 'kuishan': 'KAB', 'kuitan': 'KTQ', 'kuitun': 'KTR', 'kulun': 'KLD', 'kunming': 'KMM', 'kunmingxi': 'KXM', 'kunshan': 'KSH', 'kunshannan': 'KNH', 'kunyang': 'KAM', 'lagu': 'LGB', 'laha': 'LHX', 'laibin': 'UBZ', 'laibinbei': 'UCZ', 'laituan': 'LVZ', 'laiwudong': 'LWK', 'laiwuxi': 'UXK', 'laixi': 'LXK', 'laixibei': 'LBK', 'laiyang': 'LYK', 'laiyuan': 'LYP', 'laizhou': 'LZS', 'lalin': 'LAB', 'lamadian': 'LMX', 'lancun': 'LCK', 'langang': 'LNB', 'langfang': 'LJP', 'langfangbei': 'LFP', 'langweishan': 'LRJ', 'langxiang': 'LXB', 'langzhong': 'LZE', 'lankao': 'LKF', 'lankaonan': 'LUF', 'lanling': 'LLB', 'lanlingbei': 'COK', 'lanxi': 'LWH', 'lanzhou': 'LZJ', 'lanzhoudong': 'LVJ', 'lanzhouxi': 'LAJ', 'lanzhouxinqu': 'LQJ', 'laobian': 'LLT', 'laochengzhen': 'ACQ', 'laofu': 'UFD', 'laolai': 'LAX', 'laoying': 'LXL', 'lasa': 'LSO', 'lazha': 'LEM', 'lechang': 'LCQ', 'ledong': 'UQQ', 'ledu': 'LDO', 'ledunan': 'LVO', 'leiyang': 'LYQ', 'leiyangxi': 'LPQ', 'leizhou': 'UAQ', 'lengshuijiangdong': 'UDQ', 'lepingshi': 'LPG', 'leshan': 'IVW', 'leshanbei': 'UTW', 'leshancun': 'LUM', 'liangdang': 'LDY', 'liangdixia': 'LDP', 'lianggezhuang': 'LGP', 'liangjia': 'UJT', 'liangjiadian': 'LRT', 'liangping': 'UQW', 'liangpingnan': 'LPE', 'liangshan': 'LMK', 'lianjiang': 'LJZ', 'lianjiangkou': 'LHB', 'lianshanguan': 'LGT', 'lianyuan': 'LAQ', 'lianyungang': 'UIH', 'lianyungangdong': 'UKH', 'liaocheng': 'UCK', 'liaoyang': 'LYT', 'liaoyuan': 'LYL', 'liaozhong': 'LZD', 'licheng': 'UCP', 'lichuan': 'LCN', 'liduigongyuan': 'INW', 'lijia': 'LJB', 'lijiang': 'LHM', 'lijiaping': 'LIJ', 'lijinnan': 'LNK', 'lilinbei': 'KBQ', 'liling': 'LLG', 'lilingdong': 'UKQ', 'limudian': 'LMB', 'lincheng': 'UUP', 'linchuan': 'LCG', 'lindong': 'LRC', 'linfen': 'LFV', 'linfenxi': 'LXV', 'lingaonan': 'KGQ', 'lingbao': 'LBF', 'lingbaoxi': 'LPF', 'lingbi': 'GMH', 'lingcheng': 'LGK', 'linghai': 'JID', 'lingling': 'UWZ', 'lingqiu': 'LVV', 'lingshi': 'LSV', 'lingshidong': 'UDV', 'lingshui': 'LIQ', 'lingwu': 'LNJ', 'lingyuan': 'LYD', 'lingyuandong': 'LDD', 'linhai': 'UFH', 'linhe': 'LHC', 'linjialou': 'ULK', 'linjiang': 'LQL', 'linkou': 'LKB', 'linli': 'LWQ', 'linqing': 'UQK', 'linshengpu': 'LBT', 'linxi': 'LXC', 'linxiang': 'LXQ', 'linyi': 'LVK', 'linyibei': 'UYK', 'linying': 'LNF', 'linyuan': 'LYX', 'linze': 'LEJ', 'linzenan': 'LDJ', 'liquan': 'LGY', 'lishizhai': 'LET', 'lishui': 'LDH', 'lishuzhen': 'LSB', 'litang': 'LTZ', 'liudaohezi': 'LVP', 'liuhe': 'LNL', 'liuhezhen': 'LEX', 'liujiadian': 'UDT', 'liujiahe': 'LVT', 'liulinnan': 'LKV', 'liupanshan': 'UPJ', 'liupanshui': 'UMW', 'liushuigou': 'USP', 'liushutun': 'LSD', 'liuyuan': 'DHR', 'liuyuannan': 'LNR', 'liuzhi': 'LIW', 'liuzhou': 'LZZ', 'liwang': 'VLJ', 'lixian': 'LEQ', 'liyang': 'LEH', 'lizhi': 'LZX', 'longandong': 'IDZ', 'longchang': 'LCW', 'longchangbei': 'NWW', 'longchuan': 'LUQ', 'longdongbao': 'FVW', 'longfeng': 'KFQ', 'longgou': 'LGJ', 'longgudian': 'LGM', 'longhua': 'UHP', 'longjia': 'UJL', 'longjiang': 'LJX', 'longjing': 'LJL', 'longli': 'LLW', 'longlibei': 'KFW', 'longnan': 'UNG', 'longquansi': 'UQJ', 'longshanzhen': 'LAS', 'longshi': 'LAG', 'longtangba': 'LBM', 'longxi': 'LXJ', 'longxian': 'LXY', 'longyan': 'LYS', 'longyou': 'LMH', 'longzhen': 'LZA', 'longzhuagou': 'LZT', 'loudi': 'LDQ', 'loudinan': 'UOQ', 'luan': 'UAH', 'luanhe': 'UDP', 'luanheyan': 'UNP', 'luanping': 'UPP', 'luanxian': 'UXP', 'luchaogang': 'UCH', 'lucheng': 'UTP', 'luchuan': 'LKZ', 'ludao': 'LDL', 'lueyang': 'LYY', 'lufan': 'LVM', 'lufeng': 'LLQ', 'lufengnan': 'LQM', 'lugou': 'LOM', 'lujiang': 'UJH', 'lukoupu': 'LKQ', 'luliang': 'LRM', 'lulong': 'UAP', 'luntai': 'LAR', 'luocheng': 'VCZ', 'luofa': 'LOP', 'luohe': 'LON', 'luohexi': 'LBN', 'luojiang': 'LJW', 'luojiangdong': 'IKW', 'luomen': 'LMJ', 'luoping': 'LPM', 'luopoling': 'LPP', 'luoshan': 'LRN', 'luotuoxiang': 'LTJ', 'luowansanjiang': 'KRW', 'luoyang': 'LYF', 'luoyangdong': 'LDF', 'luoyanglongmen': 'LLF', 'luoyuan': 'LVS', 'lushan': 'LSG', 'lushuihe': 'LUL', 'lutai': 'LTP', 'luxi': 'LUG', 'luzhai': 'LIZ', 'luzhaibei': 'LSZ', 'lvboyuan': 'LCF', 'lvhua': 'LWJ', 'lvliang': 'LHV', 'lvshun': 'LST', 'maanshan': 'MAH', 'maanshandong': 'OMH', 'macheng': 'MCN', 'machengbei': 'MBN', 'mahuang': 'MHZ', 'maiyuan': 'MYS', 'malan': 'MLR', 'malianhe': 'MHB', 'malin': 'MID', 'malong': 'MGM', 'manasi': 'MSR', 'manasihu': 'MNR', 'mangui': 'MHX', 'manshuiwan': 'MKW', 'manzhouli': 'MLX', 'maoba': 'MBY', 'maobaguan': 'MGY', 'maocaoping': 'KPM', 'maoershan': 'MRB', 'maolin': 'MLD', 'maoling': 'MLZ', 'maoming': 'MDQ', 'maomingxi': 'MMZ', 'maoshezu': 'MOM', 'maqiaohe': 'MQB', 'masanjia': 'MJT', 'mashan': 'MAB', 'mawei': 'VAW', 'mayang': 'MVQ', 'meihekou': 'MHL', 'meilan': 'MHQ', 'meishan': 'MSW', 'meishandong': 'IUW', 'meixi': 'MEB', 'meizhou': 'MOQ', 'mengdonghe': 'MUQ', 'mengjiagang': 'MGB', 'mengzhuang': 'MZF', 'mengzi': 'MZM', 'mengzibei': 'MBM', 'menyuan': 'MYO', 'mianchi': 'MCF', 'mianchinan': 'MNF', 'mianduhe': 'MDX', 'mianning': 'UGW', 'mianxian': 'MVY', 'mianyang': 'MYW', 'miaocheng': 'MAP', 'miaoling': 'MLL', 'miaoshan': 'MSN', 'miaozhuang': 'MZJ', 'midu': 'MDF', 'miluo': 'MLQ', 'miluodong': 'MQQ', 'mingcheng': 'MCL', 'minggang': 'MGN', 'minggangdong': 'MDN', 'mingguang': 'MGH', 'mingshuihe': 'MUT', 'mingzhu': 'MFQ', 'minhenan': 'MNO', 'minle': 'MBJ', 'minqing': 'MQS', 'minqingbei': 'MBS', 'minquan': 'MQF', 'minquanbei': 'MIF', 'mishan': 'MSB', 'mishazi': 'MST', 'miyi': 'MMW', 'miyunbei': 'MUP', 'mizhi': 'MEY', 'modaoshi': 'MOB', 'moerdaoga': 'MRX', 'mohe': 'MVX', 'moyu': 'MUR', 'mudanjiang': 'MDB', 'muling': 'MLB', 'mulitu': 'MUD', 'mupang': 'MPQ', 'muping': 'MBK', 'nailin': 'NLD', 'naiman': 'NMD', 'naluo': 'ULZ', 'nanboshan': 'NBK', 'nanbu': 'NBE', 'nancao': 'NEF', 'nancha': 'NCB', 'nanchang': 'NCG', 'nanchangxi': 'NXG', 'nancheng': 'NDG', 'nanchengsi': 'NSP', 'nanchong': 'NCW', 'nanchongbei': 'NCE', 'nandamiao': 'NMP', 'nandan': 'NDZ', 'nanfen': 'NFT', 'nanfenbei': 'NUT', 'nanfeng': 'NFG', 'nangongdong': 'NFP', 'nanguancun': 'NGP', 'nanguanling': 'NLT', 'nanhechuan': 'NHJ', 'nanhua': 'NHS', 'nanhudong': 'NDN', 'nanjiang': 'FIW', 'nanjiangkou': 'NDQ', 'nanjing': 'NJH', 'nanjingnan': 'NKH', 'nankou': 'NKP', 'nankouqian': 'NKT', 'nanlang': 'NNQ', 'nanling': 'LLH', 'nanmu': 'NMX', 'nanning': 'NNZ', 'nanningdong': 'NFZ', 'nanningxi': 'NXZ', 'nanping': 'NPS', 'nanpingbei': 'NBS', 'nanpingnan': 'NNS', 'nanqiao': 'NQD', 'nanqiu': 'NCK', 'nantai': 'NTT', 'nantong': 'NUH', 'nantou': 'NOQ', 'nanwanzi': 'NWP', 'nanxiangbei': 'NEH', 'nanxiong': 'NCQ', 'nanyang': 'NFF', 'nanyangzhai': 'NYF', 'nanyu': 'NUP', 'nanzamu': 'NZT', 'nanzhao': 'NAF', 'napu': 'NPZ', 'naqu': 'NQO', 'nayong': 'NYE', 'nehe': 'NHX', 'neijiang': 'NJW', 'neijiangbei': 'NKW', 'neixiang': 'NXF', 'nengjia': 'NJD', 'nenjiang': 'NGX', 'niangziguan': 'NIP', 'nianzishan': 'NZX', 'nihezi': 'NHD', 'nileke': 'NIR', 'nimu': 'NMO', 'ningan': 'NAB', 'ningbo': 'NGH', 'ningbodong': 'NVH', 'ningcun': 'NCZ', 'ningde': 'NES', 'ningdong': 'NOJ', 'ningdongnan': 'NDJ', 'ningguo': 'NNH', 'ninghai': 'NHH', 'ningjia': 'NVT', 'ninglingxian': 'NLF', 'ningming': 'NMZ', 'ningwu': 'NWV', 'ningxiang': 'NXQ', 'niujia': 'NJB', 'niuxintai': 'NXT', 'nongan': 'NAT', 'nuanquan': 'NQJ', 'paihuaibei': 'PHP', 'pananzhen': 'PAJ', 'panguan': 'PAM', 'panjiadian': 'PDP', 'panjin': 'PVD', 'panjinbei': 'PBD', 'panshi': 'PSL', 'panzhihua': 'PRW', 'panzhou': 'PAE', 'paozi': 'POD', 'peide': 'PDB', 'pengan': 'PAW', 'pengshan': 'PSW', 'pengshanbei': 'PPW', 'pengshui': 'PHW', 'pengyang': 'PYJ', 'pengze': 'PZG', 'pengzhou': 'PMW', 'piandian': 'PRP', 'pianling': 'PNT', 'piaoertun': 'PRT', 'pikou': 'PUT', 'pikounan': 'PKT', 'pingan': 'PAL', 'pinganyi': 'PNO', 'pinganzhen': 'PZT', 'pingbanan': 'PBE', 'pingbian': 'PBM', 'pingchang': 'PCE', 'pingdingshan': 'PEN', 'pingdingshanxi': 'BFF', 'pingdu': 'PAK', 'pingfang': 'PFB', 'pinggang': 'PGL', 'pingguan': 'PGM', 'pingguo': 'PGZ', 'pinghekou': 'PHM', 'pinghu': 'PHQ', 'pingliang': 'PIJ', 'pingliangnan': 'POJ', 'pingnannan': 'PAZ', 'pingquan': 'PQP', 'pingshan': 'PSB', 'pingshang': 'PSK', 'pingshe': 'PSV', 'pingshi': 'PSQ', 'pingtai': 'PVT', 'pingtian': 'PTM', 'pingwang': 'PWV', 'pingxiang': 'PXZ', 'pingxiangbei': 'PBG', 'pingxingguan': 'PGV', 'pingyang': 'PYX', 'pingyao': 'PYV', 'pingyaogucheng': 'PDV', 'pingyi': 'PIK', 'pingyu': 'PYP', 'pingyuan': 'PYK', 'pingyuanpu': 'PPJ', 'pingzhuang': 'PZD', 'pingzhuangnan': 'PND', 'pishan': 'PSR', 'pixian': 'PWW', 'pixianxi': 'PCW', 'pizhou': 'PJH', 'podixia': 'PXJ', 'puan': 'PAN', 'puanxian': 'PUE', 'pucheng': 'PCY', 'puchengdong': 'PEY', 'puding': 'PGW', 'pulandian': 'PLT', 'puning': 'PEQ', 'putaojing': 'PTW', 'putian': 'PTS', 'puwan': 'PWT', 'puxiong': 'POW', 'puyang': 'PYF', 'qianan': 'QOT', 'qianfeng': 'QFB', 'qianhe': 'QUY', 'qianjiang': 'QJN', 'qianjinzhen': 'QEB', 'qianmotou': 'QMP', 'qianshan': 'QXQ', 'qianwei': 'QWD', 'qianweitang': 'QWP', 'qianxian': 'QBY', 'qianyang': 'QOY', 'qiaotou': 'QAT', 'qiaoxi': 'QXJ', 'qichun': 'QRN', 'qidian': 'QDM', 'qidong': 'QMQ', 'qidongbei': 'QRQ', 'qifengta': 'QVP', 'qijiang': 'QJW', 'qijiapu': 'QBT', 'qilihe': 'QLD', 'qimen': 'QIH', 'qingan': 'QAB', 'qingbaijiangdong': 'QFW', 'qingchengshan': 'QSW', 'qingdao': 'QDK', 'qingdaobei': 'QHK', 'qingdui': 'QET', 'qingfeng': 'QFT', 'qinghe': 'QIP', 'qinghecheng': 'QYP', 'qinghemen': 'QHD', 'qinghuayuan': 'QHP', 'qingjianxian': 'QNY', 'qinglian': 'QEW', 'qinglong': 'QIB', 'qinglongshan': 'QGH', 'qingshan': 'QSB', 'qingshen': 'QVW', 'qingsheng': 'QSQ', 'qingshui': 'QUJ', 'qingshuibei': 'QEJ', 'qingtian': 'QVH', 'qingtongxia': 'QTJ', 'qingxian': 'QXP', 'qingxu': 'QUV', 'qingyangshan': 'QSJ', 'qingyuan': 'QYT', 'qingzhoushi': 'QZK', 'qinhuangdao': 'QTP', 'qinjia': 'QJB', 'qinjiazhuang': 'QZV', 'qinling': 'QLY', 'qinxian': 'QVV', 'qinyang': 'QYF', 'qinzhou': 'QRZ', 'qinzhoudong': 'QDZ', 'qionghai': 'QYQ', 'qiqihaer': 'QHX', 'qiqihaernan': 'QNB', 'qishan': 'QAY', 'qishuyan': 'QYH', 'qitaihe': 'QTB', 'qixian': 'QXV', 'qixiandong': 'QGV', 'qixiaying': 'QXC', 'qiyang': 'QWQ', 'qiyangbei': 'QVQ', 'qiying': 'QYJ', 'qiziwan': 'QZQ', 'quanjiao': 'INH', 'quanyang': 'QYL', 'quanzhou': 'QYS', 'quanzhoudong': 'QRS', 'quanzhounan': 'QNZ', 'queshan': 'QSN', 'qufu': 'QFK', 'qufudong': 'QAK', 'qujiang': 'QIM', 'qujing': 'QJM', 'qujiu': 'QJZ', 'quli': 'QLZ', 'qushuixian': 'QSO', 'quxian': 'QRW', 'quzhou': 'QEH', 'raoping': 'RVQ', 'raoyang': 'RVP', 'raoyanghe': 'RHD', 'renbu': 'RUO', 'renqiu': 'RQP', 'reshui': 'RSD', 'rikaze': 'RKO', 'rizhao': 'RZK', 'rongan': 'RAZ', 'rongchang': 'RCW', 'rongchangbei': 'RQW', 'rongcheng': 'RCK', 'ronggui': 'RUQ', 'rongjiang': 'RVW', 'rongshui': 'RSZ', 'rongxian': 'RXZ', 'rudong': 'RIH', 'rugao': 'RBH', 'ruian': 'RAH', 'ruichang': 'RCG', 'ruijin': 'RJG', 'rujigou': 'RQJ', 'rushan': 'ROK', 'ruyang': 'RYF', 'ruzhou': 'ROF', 'saihantala': 'SHC', 'salaqi': 'SLC', 'sandaohu': 'SDL', 'sanduxian': 'KKW', 'sanggendalai': 'OGC', 'sanguankou': 'OKJ', 'sangyuanzi': 'SAJ', 'sanhexian': 'OXP', 'sanhezhuang': 'SVP', 'sanhuizhen': 'OZW', 'sanjiadian': 'ODP', 'sanjianfang': 'SFX', 'sanjiangkou': 'SKD', 'sanjiangnan': 'SWZ', 'sanjiangxian': 'SOZ', 'sanjiazhai': 'SMM', 'sanjingzi': 'OJT', 'sanmenxia': 'SMF', 'sanmenxian': 'OQH', 'sanmenxianan': 'SCF', 'sanmenxiaxi': 'SXF', 'sanming': 'SMS', 'sanmingbei': 'SHS', 'sanshijia': 'SRD', 'sanshilipu': 'SST', 'sanshui': 'SJQ', 'sanshuibei': 'ARQ', 'sanshuinan': 'RNQ', 'sansui': 'QHW', 'santangji': 'SDH', 'sanya': 'JUQ', 'sanyangchuan': 'SYJ', 'sanyijing': 'OYD', 'sanying': 'OEJ', 'sanyuan': 'SAY', 'sanyuanpu': 'SYL', 'shache': 'SCR', 'shacheng': 'SCP', 'shahai': 'SED', 'shahe': 'SHP', 'shahekou': 'SKT', 'shaheshi': 'VOP', 'shahousuo': 'SSD', 'shalingzi': 'SLP', 'shanchengzhen': 'SCL', 'shandan': 'SDJ', 'shangbancheng': 'SBP', 'shangbanchengnan': 'OBP', 'shangcheng': 'SWN', 'shangdu': 'SXC', 'shanggaozhen': 'SVK', 'shanghai': 'SHH', 'shanghaihongqiao': 'AOH', 'shanghainan': 'SNH', 'shanghaixi': 'SXH', 'shanghang': 'JBS', 'shanghe': 'SOK', 'shangjia': 'SJB', 'shangluo': 'OLY', 'shangnan': 'ONY', 'shangqiu': 'SQF', 'shangqiunan': 'SPF', 'shangrao': 'SRG', 'shangwan': 'SWP', 'shangxipu': 'SXM', 'shangyaodun': 'SPJ', 'shangyu': 'BDH', 'shangyuan': 'SUD', 'shangyubei': 'SSH', 'shangzhi': 'SZB', 'shanhaiguan': 'SHD', 'shanhetun': 'SHL', 'shanpodong': 'SBN', 'shanshan': 'SSR', 'shanshanbei': 'SMR', 'shanshi': 'SQB', 'shantou': 'OTQ', 'shanwei': 'OGQ', 'shanyin': 'SNV', 'shaodong': 'SOQ', 'shaoguan': 'SNQ', 'shaoguandong': 'SGQ', 'shaojiatang': 'SJJ', 'shaoshan': 'SSQ', 'shaoshannan': 'INQ', 'shaowu': 'SWS', 'shaoxing': 'SOH', 'shaoxingbei': 'SLH', 'shaoyang': 'SYQ', 'shaoyangbei': 'OVQ', 'shapotou': 'SFJ', 'shaqiao': 'SQM', 'shatuo': 'SFM', 'shawanxian': 'SXR', 'shaxian': 'SAS', 'shelihu': 'VLD', 'shenchi': 'SMV', 'shenfang': 'OLH', 'shengfang': 'SUP', 'shenjia': 'OJB', 'shenjiahe': 'OJJ', 'shenjingzi': 'SWT', 'shenmu': 'OMY', 'shenqiu': 'SQN', 'shenshu': 'SWB', 'shentou': 'SEV', 'shenyang': 'SYT', 'shenyangbei': 'SBT', 'shenyangdong': 'SDT', 'shenyangnan': 'SOT', 'shenzhen': 'SZQ', 'shenzhenbei': 'IOQ', 'shenzhendong': 'BJQ', 'shenzhenpingshan': 'IFQ', 'shenzhenxi': 'OSQ', 'shenzhou': 'OZP', 'shexian': 'OEP', 'shexianbei': 'NPH', 'shiba': 'OBJ', 'shibing': 'AQW', 'shiboyuan': 'ZWT', 'shicheng': 'SCT', 'shidu': 'SEP', 'shihezi': 'SZR', 'shijiazhuang': 'SJP', 'shijiazhuangbei': 'VVP', 'shijiazi': 'SJD', 'shijiazui': 'SHM', 'shijingshannan': 'SRP', 'shilidian': 'OMP', 'shilin': 'SPB', 'shiling': 'SOL', 'shilinnan': 'LNM', 'shilong': 'SLQ', 'shimenxian': 'OMQ', 'shimenxianbei': 'VFQ', 'shiqiao': 'SQE', 'shiqiaozi': 'SQT', 'shiquanxian': 'SXY', 'shiren': 'SRL', 'shirencheng': 'SRB', 'shishan': 'SAD', 'shishanbei': 'NSQ', 'shiti': 'STE', 'shitou': 'OTB', 'shixian': 'SXL', 'shixiazi': 'SXJ', 'shixing': 'IPQ', 'shiyan': 'SNN', 'shizhuang': 'SNM', 'shizhuxian': 'OSW', 'shizong': 'SEM', 'shizuishan': 'QQJ', 'shoushan': 'SAT', 'shouyang': 'SYV', 'shuangchengbei': 'SBB', 'shuangchengpu': 'SCB', 'shuangfeng': 'OFB', 'shuangfengbei': 'NFQ', 'shuanghezhen': 'SEL', 'shuangliao': 'ZJD', 'shuangliujichang': 'IPW', 'shuangliuxi': 'IQW', 'shuangpai': 'SBZ', 'shuangyashan': 'SSB', 'shucheng': 'OCH', 'shuidong': 'SIL', 'shuifu': 'OTW', 'shuijiahu': 'SQH', 'shuiquan': 'SID', 'shuiyang': 'OYP', 'shuiyuan': 'OYJ', 'shulan': 'SLL', 'shule': 'SUR', 'shulehe': 'SHJ', 'shunchang': 'SCS', 'shunde': 'ORQ', 'shundexueyuan': 'OJQ', 'shunyi': 'SOP', 'shuozhou': 'SUV', 'shuyang': 'FMH', 'sidaowan': 'OUD', 'sifangtai': 'STB', 'siheyong': 'OHD', 'sihong': 'GQH', 'sihui': 'AHQ', 'sijialing': 'OLK', 'siping': 'SPT', 'sipingdong': 'PPT', 'sishui': 'OSK', 'sixian': 'GPH', 'siyang': 'MPH', 'song': 'SOB', 'songchenglu': 'SFF', 'songhe': 'SBM', 'songjiang': 'SAH', 'songjianghe': 'SJL', 'songjiangnan': 'IMH', 'songjiangzhen': 'OZL', 'songshu': 'SFT', 'songshuzhen': 'SSL', 'songtao': 'MZQ', 'songyuan': 'VYT', 'songyuanbei': 'OCT', 'songzi': 'SIN', 'suide': 'ODY', 'suifenhe': 'SFB', 'suihua': 'SHB', 'suiling': 'SIB', 'suining': 'NIW', 'suiping': 'SON', 'suixi': 'SXZ', 'suiyang': 'SYB', 'suizhong': 'SZD', 'suizhongbei': 'SND', 'suizhou': 'SZN', 'sujiatun': 'SXT', 'suning': 'SYP', 'sunjia': 'SUB', 'sunwu': 'SKB', 'sunzhen': 'OZY', 'suolun': 'SNT', 'suotuhan': 'SHX', 'susong': 'OAH', 'suzhou': 'SZH', 'suzhoubei': 'OHH', 'suzhoudong': 'SRH', 'suzhouxinqu': 'ITH', 'suzhouyuanqu': 'KAH', 'taerqi': 'TVX', 'taha': 'THX', 'tahe': 'TXX', 'taian': 'TID', 'taigu': 'TGV', 'taiguxi': 'TIV', 'taihe': 'THG', 'taihu': 'TKH', 'taikang': 'TKX', 'tailai': 'TLX', 'taimushan': 'TLS', 'taining': 'TNS', 'taipingchuan': 'TIT', 'taipingzhen': 'TEB', 'taiqian': 'TTK', 'taishan': 'TAK', 'taiyangshan': 'TYJ', 'taiyangsheng': 'TQT', 'taiyuan': 'TYV', 'taiyuanbei': 'TBV', 'taiyuandong': 'TDV', 'taiyuannan': 'TNV', 'taizhou': 'TZH', 'tancheng': 'TZK', 'tangbao': 'TBQ', 'tangchi': 'TCX', 'tanggu': 'TGP', 'tanghai': 'THM', 'tanghe': 'THF', 'tangjiawan': 'PDQ', 'tangshan': 'TSP', 'tangshanbei': 'FUP', 'tangshancheng': 'TCT', 'tangwanghe': 'THB', 'tangxunhu': 'THN', 'tangyin': 'TYF', 'tangyuan': 'TYB', 'tanjiajing': 'TNJ', 'taocun': 'TCK', 'taocunbei': 'TOK', 'taojiatun': 'TOT', 'taolaizhao': 'TPT', 'taonan': 'TVT', 'taoshan': 'TAB', 'tashizui': 'TIM', 'tayayi': 'TYP', 'tengxian': 'TAZ', 'tengzhou': 'TXK', 'tengzhoudong': 'TEK', 'tiandong': 'TDZ', 'tiandongbei': 'TBZ', 'tiangang': 'TGL', 'tianjin': 'TJP', 'tianjinbei': 'TBP', 'tianjinnan': 'TIP', 'tianjinxi': 'TXP', 'tianlin': 'TFZ', 'tianmen': 'TMN', 'tianmennan': 'TNN', 'tianqiaoling': 'TQL', 'tianshifu': 'TFT', 'tianshui': 'TSJ', 'tianyang': 'TRZ', 'tianyi': 'TND', 'tianzhen': 'TZV', 'tianzhu': 'TZJ', 'tianzhushan': 'QWH', 'tiechang': 'TCL', 'tieli': 'TLB', 'tieling': 'TLT', 'tielingxi': 'PXT', 'tingliang': 'TIZ', 'tonganyi': 'TAJ', 'tongbai': 'TBF', 'tongbei': 'TBB', 'tongcheng': 'TTH', 'tongdao': 'TRQ', 'tonggou': 'TOL', 'tongguan': 'TGY', 'tonghai': 'TAM', 'tonghua': 'THL', 'tonghuaxian': 'TXL', 'tongjiang': 'TJB', 'tongjunzhuang': 'TZP', 'tongliao': 'TLD', 'tongling': 'TJH', 'tonglingbei': 'KXH', 'tongnan': 'TVW', 'tongren': 'RDQ', 'tongrennan': 'TNW', 'tongtu': 'TUT', 'tongxiang': 'TCH', 'tongxin': 'TXJ', 'tongyuanpu': 'TYT', 'tongyuanpuxi': 'TST', 'tongzhouxi': 'TAP', 'tongzi': 'TZW', 'tongzilin': 'TEW', 'tuanjie': 'TIX', 'tuditangdong': 'TTN', 'tuguiwula': 'TGC', 'tuha': 'THR', 'tuliemaodu': 'TMD', 'tulihe': 'TEX', 'tulufan': 'TFR', 'tulufanbei': 'TAR', 'tumen': 'TML', 'tumenbei': 'QSL', 'tumenzi': 'TCJ', 'tumuertai': 'TRC', 'tuoyaoling': 'TIL', 'tuqiang': 'TQX', 'tuqiaozi': 'TQJ', 'tuxi': 'TSW', 'wafangdian': 'WDT', 'wafangdianxi': 'WXT', 'waitoushan': 'WIT', 'walagan': 'WVX', 'wanfatun': 'WFB', 'wanganzhen': 'WVP', 'wangcang': 'WEW', 'wangdu': 'WDP', 'wangfu': 'WUT', 'wanggang': 'WGB', 'wangjiawan': 'WJJ', 'wangjiayingxi': 'KNM', 'wangou': 'WGL', 'wangqing': 'WQL', 'wangtong': 'WTP', 'wangtuanzhuang': 'WZJ', 'wangyang': 'WYB', 'wangzhaotun': 'WZB', 'wanle': 'WEB', 'wannian': 'WWG', 'wanning': 'WNQ', 'wanyuan': 'WYY', 'wanzhou': 'WYW', 'wanzhoubei': 'WZE', 'wawushan': 'WAH', 'wayaotian': 'WIM', 'weidong': 'WVT', 'weifang': 'WFK', 'weihai': 'WKK', 'weihaibei': 'WHK', 'weihe': 'WHB', 'weihui': 'WHF', 'weihulingbei': 'WBL', 'weijin': 'WJL', 'weinan': 'WNY', 'weinanbei': 'WBY', 'weinannan': 'WVY', 'weinanzhen': 'WNJ', 'weiqing': 'WAM', 'weishanzhuang': 'WSP', 'weishe': 'WSM', 'weixing': 'WVB', 'weizhangzi': 'WKD', 'weizhuang': 'WZY', 'weizigou': 'WZL', 'weizizhen': 'WQP', 'wenan': 'WBP', 'wenchang': 'WEQ', 'wenchun': 'WDB', 'wendeng': 'WBK', 'wendengdong': 'WGK', 'wendi': 'WNZ', 'wenling': 'VHH', 'wenshui': 'WEV', 'wenxi': 'WXV', 'wenxixi': 'WOV', 'wenzhou': 'RZH', 'wenzhounan': 'VRH', 'woken': 'WQB', 'wolitun': 'WLX', 'wopi': 'WPT', 'wuan': 'WAP', 'wuchagou': 'WCT', 'wuchang': 'WCN', 'wudalianchi': 'WRB', 'wudangshan': 'WRN', 'wudaogou': 'WDL', 'wudaohe': 'WHP', 'wuerqihan': 'WHX', 'wufushan': 'WFG', 'wugong': 'WGY', 'wuguantian': 'WGM', 'wuhai': 'WVC', 'wuhaixi': 'WXC', 'wuhan': 'WHN', 'wuhu': 'WHH', 'wuji': 'WJP', 'wujia': 'WUB', 'wujiachuan': 'WCJ', 'wujiatun': 'WJT', 'wukeshu': 'WKT', 'wulanhada': 'WLC', 'wulanhaote': 'WWT', 'wulashan': 'WSC', 'wulateqianqi': 'WQC', 'wulian': 'WLK', 'wulong': 'WLW', 'wulongbei': 'WBT', 'wulongbeidong': 'WMT', 'wulongquannan': 'WFN', 'wulumuqi': 'WAR', 'wulumuqinan': 'WMR', 'wunuer': 'WRX', 'wunvshan': 'WET', 'wupu': 'WUY', 'wuqiao': 'WUP', 'wuqing': 'WWP', 'wushan': 'WSJ', 'wusheng': 'WSE', 'wutaishan': 'WSV', 'wuwei': 'WUJ', 'wuweinan': 'WWJ', 'wuwu': 'WVR', 'wuxi': 'WXR', 'wuxiang': 'WVV', 'wuxidong': 'WGH', 'wuxixinqu': 'IFH', 'wuxu': 'WYZ', 'wuxue': 'WXN', 'wuyi': 'RYH', 'wuyibei': 'WDH', 'wuyiling': 'WPB', 'wuying': 'WWB', 'wuyishan': 'WAS', 'wuyishanbei': 'WBS', 'wuyishandong': 'WCS', 'wuyuan': 'WYC', 'wuzhai': 'WZV', 'wuzhi': 'WIF', 'wuzhou': 'WZZ', 'wuzhounan': 'WBZ', 'xiabancheng': 'EBP', 'xiachengzi': 'XCB', 'xiaguanying': 'XGJ', 'xiahuayuan': 'XYP', 'xiajiang': 'EJG', 'xiamatang': 'XAT', 'xiamen': 'XMS', 'xiamenbei': 'XKS', 'xiamengaoqi': 'XBS', 'xian': 'XAY', 'xianbei': 'EAY', 'xiangcheng': 'ERN', 'xiangfang': 'XFB', 'xiangfen': 'XFV', 'xiangfenxi': 'XTV', 'xianghe': 'XXB', 'xianglan': 'XNB', 'xiangtan': 'XTQ', 'xiangtanbei': 'EDQ', 'xiangtang': 'XTG', 'xiangxiang': 'XXQ', 'xiangyang': 'XFN', 'xiangyangdong': 'XWN', 'xiangyuan': 'EIF', 'xiangyun': 'EXM', 'xianlin': 'XPH', 'xiannan': 'CAY', 'xianning': 'XNN', 'xianningbei': 'XRN', 'xianningdong': 'XKN', 'xianningnan': 'UNN', 'xianrenqiao': 'XRL', 'xiantaoxi': 'XAN', 'xianyang': 'XYY', 'xianyangqindu': 'XOY', 'xianyou': 'XWS', 'xiaocun': 'XEM', 'xiaodejiang': 'EJM', 'xiaodong': 'XOD', 'xiaogan': 'XGN', 'xiaoganbei': 'XJN', 'xiaoheyan': 'XYD', 'xiaohezhen': 'EKY', 'xiaojinkou': 'NKQ', 'xiaolan': 'EAQ', 'xiaoling': 'XLB', 'xiaonan': 'XNV', 'xiaoshao': 'XAM', 'xiaoshi': 'XST', 'xiaosigou': 'ESP', 'xiaoxi': 'XOV', 'xiaoxianbei': 'QSH', 'xiaoxinjie': 'XXM', 'xiaoxizhuang': 'XXP', 'xiaoyangqi': 'XYX', 'xiaoyuejiu': 'XFM', 'xiaoyugu': 'XHM', 'xiapu': 'XOS', 'xiashe': 'XSV', 'xiashi': 'XIZ', 'xiataizi': 'EIP', 'xiayixian': 'EJH', 'xibali': 'XLP', 'xichang': 'ECW', 'xichangnan': 'ENW', 'xidamiao': 'XMP', 'xide': 'EDW', 'xiehejian': 'EEP', 'xiejiazhen': 'XMT', 'xifeng': 'XFW', 'xigangzi': 'NBB', 'xigu': 'XIJ', 'xigucheng': 'XUJ', 'xihudong': 'WDQ', 'xijiekou': 'EKM', 'xilin': 'XYB', 'xilinhaote': 'XTC', 'xiliu': 'GCT', 'ximashan': 'XMB', 'xinan': 'EAM', 'xinanxian': 'XAF', 'xinbaoan': 'XAP', 'xinchengzi': 'XCT', 'xinchuoyuan': 'XRX', 'xindudong': 'EWW', 'xinfeng': 'EFG', 'xingan': 'EGG', 'xinganbei': 'XDZ', 'xingcheng': 'XCD', 'xingguo': 'EUG', 'xinghexi': 'XEC', 'xingkai': 'EKB', 'xinglongdian': 'XDD', 'xinglongxian': 'EXP', 'xinglongzhen': 'XZB', 'xingning': 'ENQ', 'xingping': 'XPY', 'xingquanbu': 'XQJ', 'xingshu': 'XSB', 'xingshutun': 'XDT', 'xingtai': 'XTP', 'xingtaidong': 'EDP', 'xingye': 'SNZ', 'xingyi': 'XRZ', 'xinhe': 'XIR', 'xinhua': 'XHB', 'xinhuanan': 'EJQ', 'xinhuang': 'XLQ', 'xinhuangxi': 'EWQ', 'xinhuatun': 'XAX', 'xinhui': 'EFQ', 'xining': 'XNO', 'xinji': 'ENP', 'xinjiang': 'XJM', 'xinjin': 'IRW', 'xinjinnan': 'ITW', 'xinle': 'ELP', 'xinli': 'XLJ', 'xinlin': 'XPX', 'xinlitun': 'XLD', 'xinlizhen': 'XGT', 'xinmin': 'XMD', 'xinpingtian': 'XPM', 'xinqing': 'XQB', 'xinqiu': 'XQD', 'xinsongpu': 'XOB', 'xinwopu': 'EPD', 'xinxian': 'XSN', 'xinxiang': 'XXF', 'xinxiangdong': 'EGF', 'xinxingxian': 'XGQ', 'xinyang': 'XUN', 'xinyangdong': 'OYN', 'xinyangzhen': 'XZJ', 'xinyi': 'EEQ', 'xinyouyi': 'EYB', 'xinyu': 'XUG', 'xinyubei': 'XBG', 'xinzhangfang': 'XZX', 'xinzhangzi': 'ERP', 'xinzhao': 'XZT', 'xinzhengjichang': 'EZF', 'xinzhou': 'XXV', 'xiongyuecheng': 'XYT', 'xiping': 'XPN', 'xipu': 'XIW', 'xipudong': 'XAW', 'xishui': 'XZN', 'xiushan': 'ETW', 'xiuwu': 'XWF', 'xiuwuxi': 'EXF', 'xiwuqi': 'XWC', 'xixia': 'XIF', 'xixian': 'ENN', 'xixiang': 'XQY', 'xixiaozhao': 'XZC', 'xiyangcun': 'XQF', 'xizhelimu': 'XRD', 'xizi': 'XZD', 'xuancheng': 'ECH', 'xuangang': 'XGV', 'xuanhan': 'XHY', 'xuanhe': 'XWJ', 'xuanhua': 'XHP', 'xuanwei': 'XWM', 'xuanzhong': 'XRP', 'xuchang': 'XCF', 'xuchangdong': 'XVF', 'xujia': 'XJB', 'xujiatai': 'XTJ', 'xujiatun': 'XJT', 'xunyang': 'XUY', 'xunyangbei': 'XBY', 'xupu': 'EPQ', 'xupunan': 'EMQ', 'xusanwan': 'XSJ', 'xushui': 'XSP', 'xuwen': 'XJQ', 'xuzhou': 'XCH', 'xuzhoudong': 'UUH', 'yabuli': 'YBB', 'yabulinan': 'YWB', 'yakeshi': 'YKX', 'yalongwan': 'TWQ', 'yanan': 'YWY', 'yancheng': 'AFH', 'yanchi': 'YAP', 'yanchuan': 'YYY', 'yandangshan': 'YGH', 'yangang': 'YGW', 'yangcao': 'YAB', 'yangcaodi': 'YKM', 'yangcha': 'YAL', 'yangchang': 'YED', 'yangcheng': 'YNF', 'yangchenghu': 'AIH', 'yangchun': 'YQQ', 'yangcun': 'YBP', 'yanggang': 'YRB', 'yanggao': 'YOV', 'yanggu': 'YIK', 'yanghe': 'GTH', 'yangjiuhe': 'YHM', 'yanglin': 'YLM', 'yangling': 'YSY', 'yanglingnan': 'YEY', 'yangliuqing': 'YQP', 'yangmingbu': 'YVV', 'yangpingguan': 'YAY', 'yangpu': 'ABM', 'yangqu': 'YQV', 'yangquan': 'AQP', 'yangquanbei': 'YPP', 'yangquanqu': 'YYV', 'yangshuling': 'YAD', 'yangshuo': 'YCZ', 'yangweishao': 'YWM', 'yangxin': 'YVK', 'yangyi': 'ARP', 'yangzhangzi': 'YZD', 'yangzhewo': 'AEM', 'yangzhou': 'YLH', 'yanhecheng': 'YHP', 'yanhui': 'AEP', 'yanji': 'YJL', 'yanjiao': 'AJP', 'yanjiazhuang': 'AZK', 'yanjin': 'AEW', 'yanjixi': 'YXL', 'yanliang': 'YNY', 'yanling': 'YAG', 'yanqi': 'YSR', 'yanqing': 'YNP', 'yanshan': 'AOP', 'yanshi': 'YSF', 'yantai': 'YAK', 'yantainan': 'YLK', 'yantongshan': 'YSL', 'yantongtun': 'YUX', 'yanzhou': 'YZK', 'yanzibian': 'YZY', 'yaoan': 'YAC', 'yaojia': 'YAT', 'yaoqianhutun': 'YQT', 'yaoshang': 'ASP', 'yatunpu': 'YTZ', 'yayuan': 'YYL', 'yazhou': 'YUQ', 'yebaishou': 'YBD', 'yecheng': 'YER', 'yesanpo': 'AIP', 'yian': 'YAX', 'yibin': 'YBW', 'yichang': 'YCN', 'yichangdong': 'HAN', 'yicheng': 'YIN', 'yichun': 'YEG', 'yichunxi': 'YCG', 'yiershi': 'YET', 'yijiang': 'RVH', 'yijianpu': 'YJT', 'yilaha': 'YLX', 'yiliang': 'ALW', 'yiliangbei': 'YSM', 'yilin': 'YLB', 'yima': 'YMF', 'yimianpo': 'YPB', 'yimianshan': 'YST', 'yimin': 'YMX', 'yinai': 'YVM', 'yinan': 'YNK', 'yinchuan': 'YIJ', 'yindi': 'YDM', 'yingbinlu': 'YFW', 'yingcheng': 'YHN', 'yingchengzi': 'YCT', 'yingchun': 'YYB', 'yingde': 'YDQ', 'yingdexi': 'IIQ', 'yingjie': 'YAM', 'yingjisha': 'YIR', 'yingkou': 'YKT', 'yingkoudong': 'YGT', 'yingpanshui': 'YZJ', 'yingshan': 'NUW', 'yingshouyingzi': 'YIP', 'yingtan': 'YTG', 'yingtanbei': 'YKG', 'yingxian': 'YZV', 'yining': 'YMR', 'yiningdong': 'YNR', 'yinlang': 'YJX', 'yinping': 'KPQ', 'yintan': 'CTQ', 'yishui': 'YUK', 'yitulihe': 'YEX', 'yiwu': 'YWH', 'yixian': 'YXD', 'yixing': 'YUH', 'yiyang': 'YIG', 'yizheng': 'UZH', 'yizhou': 'YSZ', 'yizi': 'YQM', 'yongan': 'YAS', 'yonganxiang': 'YNB', 'yongchengbei': 'RGH', 'yongchuan': 'YCW', 'yongchuandong': 'WMW', 'yongdeng': 'YDJ', 'yongding': 'YGS', 'yongfengying': 'YYM', 'yongfunan': 'YBZ', 'yongji': 'YIV', 'yongjia': 'URH', 'yongjibei': 'AJV', 'yongkang': 'RFH', 'yongkangnan': 'QUH', 'yonglang': 'YLW', 'yongledian': 'YDY', 'yongshou': 'ASY', 'yongtai': 'YTS', 'yongxiu': 'ACG', 'yongzhou': 'AOQ', 'youhao': 'YOB', 'youxi': 'YXS', 'youxian': 'YOG', 'youxiannan': 'YXG', 'youyang': 'AFW', 'yuanbaoshan': 'YUD', 'yuandun': 'YAJ', 'yuanmou': 'YMM', 'yuanping': 'YPV', 'yuanqian': 'AQK', 'yuanshi': 'YSP', 'yuantan': 'YTQ', 'yuanyangzhen': 'YYJ', 'yucheng': 'YCK', 'yuchengxian': 'IXH', 'yuci': 'YCV', 'yudu': 'YDG', 'yuechi': 'AWW', 'yuejiajing': 'YGJ', 'yueliangtian': 'YUM', 'yueqing': 'UPH', 'yueshan': 'YBF', 'yuexi': 'YHW', 'yueyang': 'YYQ', 'yueyangdong': 'YIQ', 'yuge': 'VTM', 'yuhang': 'EVH', 'yujiang': 'YHG', 'yujiapu': 'YKP', 'yuliangpu': 'YLD', 'yulin': 'ALY', 'yumen': 'YXJ', 'yunan': 'YKQ', 'yuncailing': 'ACP', 'yuncheng': 'YPK', 'yunchengbei': 'ABV', 'yundonghai': 'NAQ', 'yunfudong': 'IXQ', 'yunjusi': 'AFP', 'yunlianghe': 'YEF', 'yunmeng': 'YMN', 'yunshan': 'KZQ', 'yunxiao': 'YBS', 'yuping': 'YZW', 'yuquan': 'YQB', 'yushan': 'YNG', 'yushannan': 'YGG', 'yushe': 'AUM', 'yushi': 'YSJ', 'yushu': 'YRT', 'yushugou': 'YGP', 'yushutai': 'YUT', 'yushutun': 'YSX', 'yutianxian': 'ATP', 'yuxi': 'YXM', 'yuyao': 'YYH', 'yuyaobei': 'CTH', 'zaolin': 'ZIV', 'zaoqiang': 'ZVP', 'zaoyang': 'ZYN', 'zaozhuang': 'ZEK', 'zaozhuangdong': 'ZNK', 'zaozhuangxi': 'ZFK', 'zengjiapingzi': 'ZBW', 'zengkou': 'ZKE', 'zepu': 'ZPR', 'zerunli': 'ZLM', 'zhalainuoerxi': 'ZXX', 'zhalantun': 'ZTX', 'zhalute': 'ZLD', 'zhangbaiwan': 'ZUP', 'zhangdang': 'ZHT', 'zhanggutai': 'ZGD', 'zhangjiajie': 'DIQ', 'zhangjiakou': 'ZKP', 'zhangjiakounan': 'ZMP', 'zhanglan': 'ZLV', 'zhangmutou': 'ZOQ', 'zhangmutoudong': 'ZRQ', 'zhangping': 'ZPS', 'zhangpu': 'ZCS', 'zhangqiao': 'ZQY', 'zhangqiu': 'ZTK', 'zhangshu': 'ZSG', 'zhangshudong': 'ZOG', 'zhangweitun': 'ZWB', 'zhangwu': 'ZWD', 'zhangxin': 'ZIP', 'zhangye': 'ZYJ', 'zhangyexi': 'ZEJ', 'zhangzhou': 'ZUS', 'zhangzhoudong': 'GOS', 'zhanjiang': 'ZJZ', 'zhanjiangxi': 'ZWQ', 'zhaoan': 'ZDS', 'zhaobai': 'ZBP', 'zhaocheng': 'ZCV', 'zhaodong': 'ZDB', 'zhaofupu': 'ZFM', 'zhaoguang': 'ZGB', 'zhaohua': 'ZHW', 'zhaoqing': 'ZVQ', 'zhaoqingdong': 'FCQ', 'zhaotong': 'ZDW', 'zhashui': 'ZSY', 'zhazi': 'ZAL', 'zhelimu': 'ZLC', 'zhenan': 'ZEY', 'zhenchengdi': 'ZDV', 'zhengding': 'ZDP', 'zhengdingjichang': 'ZHP', 'zhengxiangbaiqi': 'ZXC', 'zhengzhou': 'ZZF', 'zhengzhoudong': 'ZAF', 'zhengzhouxi': 'XPF', 'zhenjiang': 'ZJH', 'zhenjiangnan': 'ZEH', 'zhenlai': 'ZLT', 'zhenping': 'ZPF', 'zhenxi': 'ZVT', 'zhenyuan': 'ZUW', 'zhian': 'ZAD', 'zhicheng': 'ZCN', 'zhifangdong': 'ZMN', 'zhijiang': 'ZPQ', 'zhijiangbei': 'ZIN', 'zhijin': 'IZW', 'zhijinbei': 'ZJE', 'zhongchuanjichang': 'ZJJ', 'zhonghe': 'ZHX', 'zhonghuamen': 'VNH', 'zhongjiacun': 'ZJY', 'zhongkai': 'KKQ', 'zhongmu': 'ZGF', 'zhongning': 'VNJ', 'zhongningdong': 'ZDJ', 'zhongningnan': 'ZNJ', 'zhongshan': 'ZSZ', 'zhongshanbei': 'ZGQ', 'zhongshanxi': 'ZAZ', 'zhongwei': 'ZWJ', 'zhongxiang': 'ZTN', 'zhongzhai': 'ZZM', 'zhoujia': 'ZOB', 'zhoujiatun': 'ZOD', 'zhoukou': 'ZKN', 'zhoushuizi': 'ZIT', 'zhuanghebei': 'ZUT', 'zhuangqiao': 'ZQH', 'zhuangzhi': 'ZUX', 'zhucheng': 'ZQK', 'zhuhai': 'ZHQ', 'zhuhaibei': 'ZIQ', 'zhuji': 'ZDH', 'zhujiagou': 'ZUB', 'zhujiawan': 'CWJ', 'zhujiayao': 'ZUJ', 'zhumadian': 'ZDN', 'zhumadianxi': 'ZLN', 'zhuozhou': 'ZXP', 'zhuozhoudong': 'ZAP', 'zhuozidong': 'ZDC', 'zhuozishan': 'ZZC', 'zhurihe': 'ZRC', 'zhuwo': 'ZOP', 'zhuyangxi': 'ZXW', 'zhuyuanba': 'ZAW', 'zhuzhou': 'ZZQ', 'zhuzhouxi': 'ZAQ', 'zibo': 'ZBK', 'zichang': 'ZHY', 'zigong': 'ZGW', 'zijingguan': 'ZYP', 'zixi': 'ZXS', 'ziyang': 'ZVY', 'ziyangbei': 'FYW', 'zizhong': 'ZZW', 'zizhongbei': 'WZW', 'zizhou': 'ZZY', 'zongxi': 'ZOY', 'zoucheng': 'ZIK', 'zunyi': 'ZIW', 'zuoling': 'ZSN'}
{"/tickets.py": ["/train.py", "/utils.py"], "/utils.py": ["/res/stations.py"]}
75,048
codeway3/tickets_tool
refs/heads/master
/tickets.py
# -*- coding: utf-8 -*- """Train tickets query via command-line. Usage: tickets (<from> <to> <date>) [-GCDTKZYOv] Options: -h,--help 显示帮助菜单 -G 高铁 -C 城际 -D 动车 -T 特快 -K 快速 -Z 直达 -Y 旅游 -O 其他 -v 调换起始车站 Example: tickets beijing shanghai 2016-08-25 tickets 北京 上海 明天 """ import os import logging import logging.handlers from train import TrainCollection from utils import logger, get_arg, get_head, get_url import requests from docopt import docopt from requests.packages.urllib3.exceptions import InsecureRequestWarning def logger_init(): path = './log' if not os.path.exists(path): os.makedirs(path) filename = path + '/all.log' fh = logging.handlers.RotatingFileHandler(filename, mode='a+', maxBytes=1048576, backupCount=3) fh.setLevel(logging.DEBUG) sh = logging.StreamHandler() sh.setLevel(logging.INFO) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[sh, fh]) def cli(): """command-line interface""" arguments = get_arg(docopt(__doc__)) url = get_url(arguments) headers = get_head() try: response = requests.get(url, verify=False, headers=headers) logger.debug(response) except Exception: logger.error('Requests error!') exit() if response.status_code == requests.codes.ok: try: res_json = response.json() except Exception: logger.error('JSON parse failed. Try again.') exit() else: logger.debug(res_json) if res_json['status']: rows = res_json['data'] # 一级解析 trains = TrainCollection(rows, arguments) # 二级解析 创建trains对象 try: trains.pretty_print() except Exception: logger.error('prettytable print failed.') exit() else: logger.error('Result not found. Please check the log.') if __name__ == '__main__': requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # 禁用安全请求警告 logger_init() cli()
{"/tickets.py": ["/train.py", "/utils.py"], "/utils.py": ["/res/stations.py"]}
75,049
codeway3/tickets_tool
refs/heads/master
/train.py
# -*- coding: utf-8 -*- from prettytable import PrettyTable def colored(color, text): table = { 'red': '\033[91m', 'green': '\033[92m', 'yellow': '\033[43m', 'blue': '\033[46m', 'purple': '\033[45m', 'nc': '\033[0m' } cv = table.get(color) nc = table.get('nc') return ''.join([cv, text, nc]) class TrainCollection(object): header = '车次 出发站,到达站 出发时间,到达时间 运行时间 商务座 一等座 二等座 软卧 硬卧 硬座 无座'.split() alpha_tab = 'G C D T K Z Y'.split() def __init__(self, tmp, arguments): self.map = tmp['map'] self.rows = tmp['result'] self.arguments = arguments def _get_duration(self, duration): duration = duration.replace(':', 'h') + 'm' if duration.startswith('00'): return duration[3:] if duration.startswith('0'): return duration[1:] return duration @property def trains(self): for tmp in self.rows: # 数据清洗 信息提取 row = tmp.split('|') train_code, start_station_code, end_station_code, from_station_code, to_station_code = row[3:8] start_time, arrive_time, duration = row[8:11] rw = row[23] wz, o, yw, yz = row[26:30] edz, ydz = row[30:32] swz = row[25] or row[32] # 特等座或商务座 在数据传输中属于两列 # 筛除停开的车次 这些车次的数据特点——起止时间均为24:00,运行时间为99h59m if int(duration.split(':')[0]) == 99: continue # 判断当日到达 次日到达 还是两日到达 dur_days = 0 if start_time > arrive_time: dur_days += 1 if int(duration.split(':')[0]) > 23: dur_days += 1 # 解析列车车次字母 if train_code[0] in self.alpha_tab: check_code = '-' + train_code[0] else: check_code = '-O' # 利用获取的信息构造train if self.arguments[check_code]: train = [ train_code, '\n'.join([(colored('yellow', '始') if start_station_code == from_station_code else colored('blue', '过')) + ' ' + colored('green', self.map[from_station_code]), (colored('purple', '终') if end_station_code == to_station_code else colored('blue', '过')) + ' ' + colored('red', self.map[to_station_code]) ]), '\n'.join([colored('green', start_time), colored('red', arrive_time)]), '\n'.join([self._get_duration(duration), '当日到达' if dur_days == 0 else '次日到达' if dur_days == 1 else '两日到达']), # 商务座 swz, # 一等座 ydz, # 二等座 edz, # 软卧 rw, # 硬卧 yw, # 硬座 yz, # 无座 wz, ] yield train def pretty_print(self): pt = PrettyTable(header=False) header = [] for x in self.header: header.append('\n'.join(x.split(','))) pt.add_row(header) for train in self.trains: pt.add_row(train) pt.align = 'l' result = pt.get_string(hrules=1) print(result)
{"/tickets.py": ["/train.py", "/utils.py"], "/utils.py": ["/res/stations.py"]}
75,050
codeway3/tickets_tool
refs/heads/master
/utils.py
import re import time import logging import logging.handlers from datetime import datetime, timedelta from res.stations import stations from res.pinyin import PinYin import requests logger = logging.getLogger(__name__) def get_arg(arguments): # 当没有传入附加参数时 将默认参数均设置为True argkeys = ['-C', '-D', '-G', '-K', '-O', '-T', '-Y', '-Z'] for key in argkeys: if arguments[key]: return arguments for key in argkeys: arguments[key] = True return arguments def get_station_info(arguments): p2e = PinYin() p2e.load_word() try: from_station = stations.get(p2e.hanzi2pinyin(string=arguments['<from>'])) to_station = stations.get(p2e.hanzi2pinyin(string=arguments['<to>'])) if '-v' in arguments and arguments['-v']: from_station, to_station = to_station, from_station if from_station is None: raise ValueError if to_station is None: raise KeyError except ValueError: logger.info('Invalid from_station name: {}'.format(arguments['<from>'])) exit() except KeyError: logger.info('Invalid to_station name: {}'.format(arguments['<to>'])) exit() else: return from_station, to_station def get_date_info(arguments): tmp_date = arguments['<date>'] trs = {'今天': 0, '明天': 1, '后天': 2, '大后天': 3, '0': 0, '1': 1, '2': 2, '3': 3} if tmp_date in trs.keys(): now = datetime.today() + timedelta(days=trs[tmp_date]) date = now.strftime('%Y-%m-%d') else: try: if len(tmp_date) == 10: date = tmp_date elif len(tmp_date) == 8: date = time.strftime('%Y-%m-%d', time.strptime(tmp_date, '%Y%m%d')) elif len(tmp_date) == 6: date = time.strftime('%Y-%m-%d', time.strptime(tmp_date, '%y%m%d')) else: raise Exception except Exception: logger.info('Invalid date: {}'.format(tmp_date)) exit() return date def get_url(arguments): html = requests.get('https://kyfw.12306.cn/otn/leftTicket/init').text url_model = 'https://kyfw.12306.cn/otn/{}?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT' query_code = re.search(r"CLeftTicketUrl = '(.*?)';", html).group(1) date = get_date_info(arguments) from_station, to_station = get_station_info(arguments) url = url_model.format( query_code, date, from_station, to_station ) return url def get_head(): headers = { 'Cookie': 'RAIL_DEVICEID=X27r3coZZsqOEYKcfbc0xY1_s5aYoCcX8-EzeZWGLUnNBaQVKrNcMwrr2ZscDxUDPEGmzyBRzcU54fvt5aDnvxRcgGhKv7hmP5LTsQiLIRZ8aN1SoBhtTgW6Zh9EBiltVGXjplRWU_IE_3OTRf7QarduXP-k6DKt;' } return headers
{"/tickets.py": ["/train.py", "/utils.py"], "/utils.py": ["/res/stations.py"]}
75,069
christian-es/kc-django-1
refs/heads/master
/blog/models.py
from django.db import models from django.contrib.auth.models import User class Categoria(models.Model): descripcion = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return self.descripcion class Articulo(models.Model): titulo = models.CharField(max_length=100) introduccion = models.CharField(max_length=150) cuerpo = models.TextField() url = models.URLField(null=True, blank=True) fecha_publicacion = models.DateField() categoria = models.ForeignKey(Categoria) created_by = models.ForeignKey(User) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return self.titulo
{"/wordplease/urls.py": ["/blog/views.py", "/users/views.py"], "/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py"]}
75,070
christian-es/kc-django-1
refs/heads/master
/users/views.py
from django.contrib.auth import authenticate, login as django_login, logout as django_logout from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.views import View class LoginView(View): def get(self, request): error_message = "" return render(request, 'users/login.html', {'error': error_message}) def post(self, request): """ Presenta el formulario de login y gestiona el login de usuario :param request: objeto HttpRequest con los datos de la petición :return: objeto HttpResponse con los datos de la respuesta """ username = request.POST.get('username') password = request.POST.get('pwd') user = authenticate(username=username, password=password) if user is None: error_message = "Datos incorrectos" else: if user.is_active: django_login(request, user) return redirect(request.GET.get('next', "/")) else: error_message = "Cuenta de usuario inactiva" context = {'error': error_message} return render(request, 'users/login.html', context) class LogoutView(View): def get(self, request): if request.user.is_authenticated(): django_logout(request) return redirect(request.GET.get('next', "/"))
{"/wordplease/urls.py": ["/blog/views.py", "/users/views.py"], "/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py"]}
75,071
christian-es/kc-django-1
refs/heads/master
/wordplease/urls.py
"""wordplease URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from blog.views import HomeView, BlogsView, PostDetailView, PostCreateView, PostListView from django.conf.urls import url from django.contrib import admin from users.views import LoginView, LogoutView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', HomeView.as_view()), url(r'^blogs/$', BlogsView.as_view()), url(r'^blogs/(?P<username>[a-zA-Z]+)$', PostListView.as_view()), url(r'^blogs/(?P<username>[a-zA-Z]+)/(?P<pk>[0-9]+)$', PostDetailView.as_view()), url(r'^blogs/post_create$', PostCreateView.as_view()), url(r'^login$', LoginView.as_view()), url(r'^logout$', LogoutView.as_view()), ]
{"/wordplease/urls.py": ["/blog/views.py", "/users/views.py"], "/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py"]}
75,072
christian-es/kc-django-1
refs/heads/master
/blog/admin.py
from blog.models import Articulo, Categoria from django.contrib import admin admin.site.register(Articulo) admin.site.register(Categoria)
{"/wordplease/urls.py": ["/blog/views.py", "/users/views.py"], "/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py"]}
75,073
christian-es/kc-django-1
refs/heads/master
/blog/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-11 19:32 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Articulo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('titulo', models.CharField(max_length=100)), ('introduccion', models.CharField(max_length=150)), ('cuerpo', models.TextField()), ('url', models.URLField(blank=True, null=True)), ('fecha_publicacion', models.DateField()), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models.DateTimeField(auto_now=True)), ], ), migrations.CreateModel( name='Categoria', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('descripcion', models.CharField(max_length=100)), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models.DateTimeField(auto_now=True)), ], ), migrations.AddField( model_name='articulo', name='categoria', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blog.Categoria'), ), migrations.AddField( model_name='articulo', name='created_by', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
{"/wordplease/urls.py": ["/blog/views.py", "/users/views.py"], "/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py"]}
75,074
christian-es/kc-django-1
refs/heads/master
/blog/views.py
from blog.forms import ArticuloForm from blog.models import Articulo from django.contrib.auth.models import User from django.http import HttpResponseNotFound, HttpResponse from django.shortcuts import render from django.views import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required class HomeView(View): def get(self, request): posts = Articulo.objects.all().order_by('-created_at') context = {'post_list': posts} return render(request, 'blog/home.html', context) class BlogsView(View): def get(self, request): usuarios = User.objects.all() context = {'usuarios_list': usuarios} return render(request, 'blog/blogs.html', context) class PostListView(View): def get(self, request, username): usuario = User.objects.filter(username=username) posts = Articulo.objects.filter(created_by_id=usuario[0].pk).order_by('-created_at') context = {'post_list': posts} return render(request, 'blog/post.html', context) class PostDetailView(View): def get(self, request, username, pk): possible_usuario = User.objects.filter(username=username) if len(possible_usuario) == 0: return HttpResponseNotFound("El usuario no existe") elif len(possible_usuario) > 1: return HttpResponse("Múltiples opciones", status=300) post = Articulo.objects.filter(pk=pk) context = {'post': post[0]} return render(request, 'blog/post_detail.html', context) class PostCreateView(View): @method_decorator(login_required()) def get(self, request): post_form = ArticuloForm() context = {'form': post_form} return render(request, 'blog/post_create.html', context) @method_decorator(login_required()) def post(self, request): message = None post_with_user = Articulo(created_by=request.user) post_form = ArticuloForm(request.POST, instance=post_with_user) if post_form.is_valid(): post_form.save() post_form = ArticuloForm() message = '<p class="bg-success">Post creado correctamente</p>' context = {'form': post_form, 'message': message} return render(request, 'blog/post_create.html', context)
{"/wordplease/urls.py": ["/blog/views.py", "/users/views.py"], "/blog/admin.py": ["/blog/models.py"], "/blog/views.py": ["/blog/models.py"]}
75,124
ashish-iitian/predicting_changes_in_stock_prices
refs/heads/master
/corr_feature_extractor.py
import numpy as np from itertools import chain class feature_extractor: def __init__(self, lag): self.lag = lag def pad_for_lag_param(self, feature_set): ''' applies padding so that the treatment for lag_param is consistent for the first set of features. For eg, for lag_param = 2, we will replicate the first entry of feature_set twice with itself. Say, feature_set = [A, B, C] where A, Band C are list of features for 3 different days. We will pad above so that it becomes [A, A, A, B, C], thus first day having (A, A, A) as features, 2nd day having (B, A, A) and 3rd day having (C, B, A) as features for lag_param=2 ''' pad = [feature_set[0] for x in xrange(self.lag)] return pad + feature_set def processor(self, feature_file): ''' processes features matrix passed by train() to implement lag_param and returns post-processed features file to train() ''' list_features = [] feature_file = self.pad_for_lag_param(feature_file) length = len(feature_file) list_features = [list(chain.from_iterable(feature_file[i:i+1+self.lag])) for i in xrange(length-self.lag)] return list_features
{"/corr_main.py": ["/corr_feature_extractor.py", "/corr_predictor.py"]}
75,125
ashish-iitian/predicting_changes_in_stock_prices
refs/heads/master
/corr_predictor.py
from sklearn.linear_model import Ridge #LinearRegression class regression: @staticmethod def learner(feat_matrix, y_train): ''' trains a linear regression model to fit to the training data set and returns learned model ''' linReg = Ridge(alpha=1) #LinearRegression() return linReg.fit(feat_matrix, y_train) @staticmethod def predictor(model, test_features): ''' runs the model on test data to return predictions by our linear regression model ''' return model.predict(test_features)
{"/corr_main.py": ["/corr_feature_extractor.py", "/corr_predictor.py"]}