Assignment 2 – Text Based Game Deadline: 16:00, Dec 12, 2024 1 Process For Assignment 2 Make sure you follow the process as outlined below. Assignment 2 has a different structure and a somewhat different approach to Assignment 1: 1. Clone the repo for assignment 2. (If you haven’t yet accessed gitlab. cs.bham . ac. uk do so ASAP.) 2. Download and unzip the docs . zip JavaDoc file to your own device. In the root folder open the IndexAll . html file. Read through all the package, class, method and field definitions and descriptions. 3. Complete each class in the src folder as defined in the docs. 4. The suggested order for completing classes is: (a) All classes in org.uob. a2. gameobjects. (b) All classes in org.uob . a2 . commands. (c) All classes in org.uob. a2.parser. (d) All classes in org.uob . a2 .utils. (e) The Game. java class. 5. For each class: (a) Complete the required code (methods and attributes). (b) Run your code using the run. sh command, ensuring it compiles without errors. (c) Test your code using the test . sh command. You will have errors at first but they should hopefully decrease as you progress. (d) git add, git commit, and git push your code. 6. Keeping testing after each class is implemented until everything is working. 7. Add the required new features: (a) Display a map. (b) Adding a score. You can decide on the rules for how the scoring works but you need to clearly explain it in the video and game. (c) Combining items. 2 Introduction In this assignment, you are tasked with updating the Zork style text based game from Assignment 1(https://en.wikipedia.org/wiki/Zork). Please note that it is likely that you will need to start from scratch due to the redesign of the game, but you ARE allowed to reuse your story and and puzzles from Assignment 1. The game is played by the user entering in various commands (e.g. "move south", "look room", "get key", "use key on chest"), to which the game responds with text based output (e.g. "You pick up the rusty key"). 3 Mark allocations You will receive marks based on two aspects of the game: Firstly, the results of run- ning the test.sh command. We will run our own version of these tests once you have submitted. This command will test each class and method (detailed as in the provided docs . zip and in Tasks 1 - 6). You need to implement all the classes and methods as described in the docs as well as any required for your new features. Secondly, you will need to submit a screen recording showing you playing the game and discussing the code. Your screen recording needs to have the following: • Show your face and your student card. • Play through the game once showing all the rooms, puzzles and an example of each of the expected commands. • Show and briefly explain the code in your Game.java file. • Show and briefly explain your required new features. • Show and briefly explain anything else that you did beyond the normal scope of the assignment. This includes any additional features you’ve added. The screen recording must be shorter than 7 minutes. You can use a text-to-speech app if you do not want to record your own voice. 3.1 Minimum expected commands The following is a completelist of commands the game must be able to parse (values in angle brackets refer to arguments given to a command, the pipe symbol refers to different options): • move : Move to a different location as defined by an exit’s name (e.g., ’move north’). • look ||| : Look around the current room, at an exit, at a feature, or, at a specific item, equipemnt or feature. • get : Pick up an item or equipment from the current room (e.g., ’get key’). • drop : Drop an item or equipment from your inventory (e.g., ’drop key’). • use on|with : Use an item in your in- ventory on its own, or on a feature or item (e.g., ’use lamp’ or ’use key on chest’). • status : Check your current status, or inventory; or get more information about a specific item or equipment in your inventory.(e.g. ’status player’, ’status inventory’, ’status key). Also able to display the map and your score. • help : Display this help information or get help on a specific topic (e.g., ’help move’ or ’help’). • combine and : Combine two items into a new item or equip- ment. (e.g., ’combine stick and rock’ or ’combine egg and flour’). • quit: Exit the game. NOTE: Some of these commands are not included in the template code and need to be added i.e. combine, status map, status score 3.2 Minimum game requirements The following are the minimum requirements for the game. You are welcome to add more if you want to: • At least ten (10) unique rooms or areas. • At least two (2) features/chests. • At least four (4) items. • At least two (2) pieces of equipment. 4 Full class hierarchy org.uob .a2 - Game org.uob .a2 .commands - Command (abstract) - Drop - Get - Help - Look - Move - Quit - Status - Use - CommandErrorException - CommandType (enum) org.uob.a2.gameobjects - GameObject (abstract) - Container (extends Feature) - Equipment (implements Usable) - Exit - Feature - Item - GameState - Player - Room - Map - Usable (interface) - UseInformation org.uob.a2.parser - Parser - Token - TokenType (enum) - Tokeniser org.uob .a2 .utils - GameStateFileParser 5 Task 1 - org.uob. a2.gameobjects These classes represent all the game objects (i.e. Map, Item etc.) that will be used in the game. The GameState class contains the current state of the game. The Container class represents anything that can "contain" another object. This is implemented as another hidden equipment or item in the room which is then revealed when the container is "opened". Usable is an interface that makes GameObjects usable by enforcing access to a GameObjects UseInformation attribute. 6 Task 2 - org.uob . a2 . commands These classes represent all the commands that the player can execute in the game and that are generated from the parser package. Commands work on the object name, not the id. This package also includes an enum of all CommandTypes and an Exception. 7 Task 3 - org.uob. a2. parser These classes convert the player’s text into into Commands that can be executed by the game. It firstly sanitises the players input to get it into a correct format. Then it converts it into Tokens using the tokenise method and finally it parses these Tokens use the parse method. 8 Task 4 - org.uob . a2 . utils These classes read in a text file (as stored in the data directory) into a GameState Object. An example of the file is shown below and also included in the data directory: player:pieter map:m1 room:r1,test room,This is a test room for testing. It is bland . ,false , equipment:k0,key,An old rusty key,false,open,c1,rb1,You use the rusty key to open the chest . Something falls to the floor. . . container:c1,chest,A solid oak chest . ,false equipment:rb1,ruby,A red ruby,true,reveal,r1,e1,You active the ruby! Hidden objects become visible! item:d1,diamond,A test diamond,false exit:e1,north,A door to the north,r2,true room:r2,second room, This is the second testing room. It is even more bland . ,false exit:e2,south,A door to the south,r1,false : player: name> map: id> ingGame playthroughGame.javaNewfeaturesmap , )Additional featuresgitlabCanvas video submissionCanvas video submissionCanvas video submissionCanvas video submission4020102010Total100
MICROCONTROLLER PROGRAMMING DIGITAL SEISMOMETER Peak Ground Acceleration (PGA) is a measure of the severity of an earthquake. The magnitude 9 Tohoku quake of 2011 had a PGA of 2.99g. Earthquake shaking generally occurs in all three directions (PGA is often split into the horizontal and vertical components) and the 3-axis data is important for earthquake engineering. Damage to buildings and infrastructure is related more closely to ground motion, of which PGA is a measure, rather than the magnitude of the earthquake itself. A digital seismometer is to be designed that measures 3-axis accelerations and transmits that data over a serial interface to a desktop personal computer. The specification of the 3-axis accelerometer to be used is given in Table 1. Supply voltage Range Offset (0g voltage) Sensitivity 5 V +/-5 g 2.5 V 0.5 V/g The sensor provides 3 analogue outputs each of whose voltage is directly proportional to acceleration in each of 3 axes. The microcontroller to be used is the C167, and each of the 3 analogue voltages needs to be connected to 3 channels of the C167’s ADC. The serial port of the C167 is to be used to stream the acceleration data as ASCII text with 2 decimal places. A comma should separate each axis and a set of 3 readings should be followed by a ‘carriage return’ character (ASCII code 13 decimal): E.g.: 1.10,1.34,-0.84 -1.24,0.65,1.22 In order to minimize time skew between the 3 individual axis readings each set of 3 readings should be converted as fast as possible. The data needs to be transmitted before the next set of readings. There should be 0.1s between subsequent sets of readings and this process should be repeated continuously. To be submitted online: Brief report. The report is to be a properly structured engineering report, typed and should explain how your program works. Wherever appropriate, please make use of flowcharts, pseudo code, state diagrams etc. to document the algorithmic details of your program. Also include Keil Simulator screenshots showing the correct operation of your Seismometer. The report and project files (zipped) with fully commented source code should be emailed to [email protected]. Use your student ID as the filename and in the header of the main program (as comment). Maintain a modular file structure, i.e. keep all Timer related functions in source file timer.c with prototypes exported through timer.h, etc.
FINAL EXAM RE-SIT FIRST SEMESTER 2021/2022 FIN 5213 FINANCIAL MARKET AND INSTITUTION SET B (FIN5213- Financial Market and Institution) This paper consists of PART A and PART B. Students are compulsory to answer a question in PART A which carries 30 marks. Meanwhile, students need to answer 3 out of 4 questions in PART B which carry 60 marks for this part. Total marks for both parts are 90. PART A (30 marks): Compulsory to answer. 1. A $1,000 face value corporate bond with a 6.5 percent coupon (paid semiannually) has 15 years left to maturity. It has had a credit rating of BBB and a yield to maturity of 7.2 percent. The firm has recently gotten into some trouble and the rating agency is downgrading the bonds to BBB. The new appropriate discount rate will be 8.5 percent. What will be the change in the bond’s price in dollars and percentage terms? (12 marks) 2. A stock you are evaluating just paid an annual dividend of $3.30. Dividends have grown at a constant rate of 1.9 percent over the last 15 years and you expect this to continue. a) If the required rate of return on the stock is 13.4 percent, what is its fair present value? If the stock sell at RM30.00, should you buy the stock? Justify your answer. (7 marks) b) If the required rate of return on the stock is 16.4 percent, what should the fair value be four years from today? (5 marks) 3. Please refer to the information about the two securities of the capital market above in (1) and (2). In your opinionwhich securities is best for your investment. Please explain your decision using 3 reasons. (6 marks) PART B (60 marks): This part consists of 4 questions. Please answer ONLY 3 questions from this part. Question 1 (20marks) 1. You have written a call option on Tesco common stock. The option has an exercise price of $75, and Walmart’s stock currently trades at $73. The option premium is $1.30 per contract. (15 marks) a) How much of the option premium is due to intrinsic value versus time value? b) What is your net profit if Tesco’s stock price decreases to $71 and stays there until the option expires? c) What is your net profit on the option if Tesco’s stock price increases to $81 at expiration of the option and the option holder exercises the option? 2. Why would a financial institution holding Tesco stock consider buying a put option on that stock rather than simply selling it? (5 marks) Question 2 (20marks) 1. Why do commercial banks hold investment securities? (5 marks) 2. Explain the dilemma faced by banks when determining the optimal amount of capital to hold. A bank’s capital is less than 10 percent of its assets. How do you think this percentage would compare to that of manufacturing corporations? How would you explain this difference? (6 marks) 3. Explain how the uniform. capital requirements can discourage banks from taking excessive risk. (5 marks) 4. Why do you think some banks suffered larger losses during the credit crisis than the other banks? Explain your answer. (4 marks) Question 3 (20marks) 1. How does a public offering differ from a private placement? (4 marks) 2. There is a specific term use for Islamic insurance. What is the term use for the insurance for Muslim? Please explain 3 features that make the product of conventional and Islamic life insurance differ. (7 marks) 3. Do all commercial borrowers receive the same interest rate on loans? (4 marks) 4. According to research, have mutual funds outperformed the market? Explain. Would mutual funds be attractive to some investors even if they are not expected to outperform the market? Explain. (5 marks) Question 4 (20marks) 1. How might expectations of higher global oil prices affect the demand for loanable funds, the supply of loanable funds, and interest rates in the United States? Will this affect the interest rates of other countries in the same way? Explain. (5 marks) 2. Assume that commercial paper is presently offering an annualized yield of 7.5 percent, while Treasury securities are offering an annualized yield of 7 percent. Economic conditions have been stable, and you expect conditions to be very favorable over the next six months. Given this situation, would you prefer to hold T-bills or a diversified portfolio of commercial paper issued by various corporations? (5 marks) 3. If the federal government planned to expand the space program, how might this affect interest rates? (5 marks) 4. In a weak economy, the government commonly implements a stimulative monetary policy to lower interest rates, and presumes that firms will be more willing to borrow. Even if banks are willing to lend, why might such a presumption about the willingness of firms to borrow be wrong? What are the consequences if the presumption is wrong? (5 marks)
EXCEL SOLVER ASSESSMENT 2024/25 ECON10151: Computing for Social Scientists November 18, 2024 1 General Instructions This assessment tests your proficiency in using the Solver function in Microsoft Excel to solve a problem based on a specified scenario. 1. Prework: The assessment information sheet is released on Monday, 18 November. On page 3, you will find details of a scenario that must be set up in Excel before attempting the Blackboard test. 2. The Blackboard Test: The Blackboard test will be available from 10am on Wednesday, 20 November, until 2pm on Fri- day, 22 November. During this window, you will have a strict 45-minute time limit to complete 10 questions once you begin the test. Extra time has been added in line with DASS requirements for eligible students. The test can be accessed in the "Assessment 1: Excel Solver" folder on the "Assessment" page of the ECON10151 Blackboard site. (a) Note that the 45-minute limit applies only to answering the test questions. You will not have time to set up the Excel scenario from scratch during the test, so it is essential to complete all preparatory tasks in advance. (b) You must complete the test in one sitting. Saving, quitting, and returning later is not allowed. (c) The test includes fill-in-the-blank and multiple-choice questions. Some questions will relatedi- rectly to the original scenario (described in Section 2 on page 3), while others may require you to adjust the original scenario and examine the effects of these changes. (d) You must have access to Excel with Solver enabled, and the worksheet containing the orig- inal scenario should be set up and open before the test begins, as you may be asked to make small adjustments to the original scenario during the test. Save all versions of your worksheet within a single Excel file for submission, with each sheet containing one scenario: the original scenario (which should remain unchanged) and additional sheets with modifications as directed during the test. (e) Questions will be randomly selected from a larger pool, so each student may receive a differ- ent set. If you have completed the prework thoroughly and are prepared for minor follow-up calculations in Excel, you should be able to complete the test confidently within the time limit. 3. Submission of the Excel Workbook: Your grade will be based on both your responses in the Blackboard test AND the submission of your Excel workbook, where you have completed all Solver calculations for each scenario. (a) Save your workbook in the following format: ‘[StudentID]workbook.xlsx ’. For example, if your student ID is 123456, name the file ‘123456workbook.xlsx ’. (b) A submission page will be available in the same folder as the Blackboard test for uploading your workbook via Turnitin. (c) The submission window is open from 10am on Wednesday, 20 November, to 2:10 pm on Friday, 22 November (10 minutes after the test closes). (d) Please note: failure to submit your Excel workbook will result in a maximum of 50% of the marks earned in the test. For example, if you score 70% in the Blackboard test and submit the Excel workbook on time, your final grade for the Excel Solver Assessment will be 70%. However, if you fail to submit the Excel workbook, your final grade for the assessment will be calculated as 70% × 0.5 = 35%. As this is an assessment, please refrain from posting any Solver assessment-related questions on Piazza during the assessment week. 2 The Solver Scenario In this scenario, you are responsible for managing the weekly grocery purchases for a small community food pantry. Your aim is to buy a balanced selection of food items that satisfy both community demand and nutritional needs. Due to budget limitations, however, the pantry can only purchase a limited quantity of each product. Based on previous data, you have estimates for the community priority score (in points),nutritional value (per kg),and cost (in £ per kg) for each item, shown in Table 1. inkg Table 1: Item Priority Scores, Nutritional Values, and Cost Due to storage and budget constraints, each item has a specified maximum weekly purchase limit, as shown in Table 2. PastaVegetablesApplesCanned SoupMilkEggsBreadChicken202025151210810207
MTH443 Advanced Topics in Operations Research Final Project Real-World Optimization Problem Solving Type: Group work Report and Slides Submission Deadline: Dec 9th (Monday) Date of Presentation: Dec 11th (Wednesday) Purpose: This coursework is designed to enhance your understanding of advanced concepts in Operations Research (OR) while applying these techniques to solve a real-world optimization problem. The goal is to develop skills in modeling, solving, and analyzing optimization problems through practical implementation. Project Overview: Each group will select a practical OR problem from a domain of their preference (e.g., logistics, supply chain, transportation, scheduling, etc.). The task involves conducting a literature review, formulating the problem mathematically, developing solution methods, performing computational experiments, and analyzing the results. The final deliverable is a concise report summarizing your findings, along with any relevant code or implementations, and a presentation on the project followed by a Q&A session. Instructions: 1. Problem Identification and Literature Review: Select a practical OR problem from a domain of your choice (e.g., logistics, supply chain, transportation, scheduling, etc.) that is relevant to the module and get approval from the teacher. Provide a clear description of the problem. Search for relevant research, and conduct a brief review of existing approaches applied to similar problems. 2. Mathematical Formulation: Formulate the mathematical model for the selected problem, specifying the objective function, constraints, and decision variables. Provide a clear explanation of the formulation, including any assumptions made. 3. Solution Method: Design and develop heuristic method(s) to effectively solve large-scale instances of the problem. Implement the chosen solution using a programming language of your choice. 4. Computational Experiments: Generate instances to test your solution method, using either real-world data or existing benchmark instances. Design and conduct experiments to evaluate the performance of the method under various scenarios, highlighting any special characteristics observed in the problem. 5. Results Analysis and Interpretation: Provide a thorough analysis of the computational results. Discuss the implications of your findings and any practical insights derived from the results. 6. Report writing: Write a report (maximum 2000 words, excluding figures, tables and appendix) that includes the following sections: o Introduction: introduce the topic and your motivation. Briefly review the relevant current research. o Problem definition and mathematical formulation: Define the problem and present the mathematical model. o Solution Method: Describe the solution methods. Use flowchart or pseudocode if needed. o Computational results: Present experiment design, results, and analysis. o Conclusions: summarize the main results and insights. o References (if any): List all references cited in your report. Make sure the citation style. is correct and consistent. o Appendix (if any):Include any additional materials. Ensure logical structure, clarity, conciseness, and formality in your writing. Include a cover page with the project title, module and coursework information, and group member information. 7. Presentation: Prepare a 15 mins presentation summarizing your project. The presentation should be concise, engaging, and well-organized, using visual aids (e.g., slides, graphs, diagrams) to support your explanation. Participate in a 5 min Q&A session. 8. Submission: LMO submission should contain the following three files: o A PDF file of your report o A ZIP file containing all your code and data o A PPT file of your presentation Name your files: [GroupID]_[Report/Code/PPT]_MTH443FinalProject.
ISE 530 Optimization Methods for Analytics Final examination Question 1 Each hour from 10AM to 7PM, Bank of America receives checks and must process them. Its goal is to process all the checks the same day they are received. The bank has 13 check-processing machines, each of which can process up to 500 checks per hour. It takes one worker to operate each machine. The bank hires both full-time and part-time workers. Full -time workers work 10AM-6PM, 11AM-7PM or Noon-8PM shifts and are paid $200 per day. Part-time workers work either 2PM-7PM or 3PM-8PM shifts and are paid $95 per day. The number of checks received each day is given in the table below. In the interest of maintaining continuity, the bank must have at least three full-time workers under contract. Formulate a linear program that finds a cost-minimizing work schedule that processes all checks by 8PM. Time Checks received 10AM 11AM Noon 1PM 2PM 3PM 4PM 5PM 6PM 7PM 5,000 4,000 3,000 4,000 2,500 3,000 4,000 4,500 3,500 3,000 Question 2 Consider the following list of points. # x y 1 4.1 -1.7 2 1.4 -0.5 3 -0.3 1.2 4 0.4 -2.5 5 0.3 -1.6 6 0.6 -0.8 7 0.8 -1.9 8 0.5 -0.3 The goal is to find a centroid (x* , y* ) that summarizes the data. In particular, we want to find the centroid and a radius ϵ such that all points in the table are within a distance of at most ϵ of the centroid. 1. Formulate a problem that finds (x* , y* ) and ϵ so that all points are at distance at most ϵ of (x* , y* ), and the radius ϵ is minimized. 2. Formulate a problem that finds (x* , y* ) and ϵ so that 6 points are at distance at most ϵ of (x* , y* ) (while the remaining two points can be arbitrarily far), and the radius ϵ is minimized. Question 3 1. Consider the optimization problem min 47x1 + 93x2 + 17x3 − 93x4 s.t. − x1 − 6x2 + x3 + 3x4 ≤ −3 − x1 − 2x2 + 7x3 + x4 ≤ 5 3x2 − 10x3 − x4 ≤ −8 − 6x1 − 11x2 − 2x3 + 12x4 ≤ −7 x1 + 6x2 − x3 − 3x4 ≤ 4. Compute its dual. 2. Consider the following linear optimization problem max 2x1 + 3x2 + 2x3 + 3x4 s.t. 2x1 + x2 + 3x3 + 2x4 ≤ 8 3x1 + 2x2 + 2x3 + x4 ≤ 7 x1,x2,x3,x4 ≥ 0, and its dual min 8y1 + 7y2 s.t. 2y1 + 3y2 ≥ 2 y1 + 2y2 ≥ 3 3y1 + 2y2 ≥ 2 2y1 + y2 ≥ 3 y1 , y2 ≥ 0. a) Write the optimality conditions b) The solution (y1 , y2 ) = (1, 1) is optimal for the dual. Using the optimality conditions, find a corresponding primal solution. Question 4 Consider the optimization problem min x1(2) + 2x2(2) − 2x1x2 − 2x2 . x1,x2∈R 1. Starting from point (x1,x2) = (0.5, 0.5), compute an iteration of steepest descent. Is the resulting point stationary? Is it optimal? 2. Starting from point (x1,x2) = (0.5, 0.5), compute an iteration of Newton method. Is the resulting point stationary? Is it optimal? 3. Consider the change of variables x3 = x1 − x2, and note that the problem can be rewritten as min x3(2) + x2(2) − 2x2. x2,x3∈R Starting from point (x2,x3) = (0.5, 0), compute an iteration of steepest descent. Is the resulting point stationary? Is it optimal?
ECO4323 TESTING CAPM — Project Report Instruction 2024 Fall 1 Logistics Congratulations! You have finished two midterm tests and all the quizzes, i.e., most of the coursework. This project report is the last piece for your evaluation. You have one week to finish the report. The deadline for submission is Dec 12, at 10:30 exactly. Be sure to submit your report on time. As we have agreed, late submissions will be penalized. Treat this take-home project as an essay with a bit of guidance. Try to solve the problem using the concepts and methodologies you learned in class, and present your work as much as you can. Data is provided to you, and detailed introductions with regard to how to understand and handle the data are provided as well. Read the instructions very carefully before you proceed. Discussions between students are encouraged, but individual report writing is required. Copy-and-paste work will be assigned zero points. 2 Exercise 2.1 Estimate Betas Financial economists and financial market participants typically estimate CAPM betas for individual stocks using 5 years of monthly data. The 5-year data sample is long enough to provide statistically precise estimates. But, by going back only 5 years, these analysts avoid using data from the more distant past that may not be relevant for predicting stock returns in the future. We will use monthly data and annual data in this exercise, both available on Moodle. In this section, we use only monthly data. The monthly data set mentioned above contains data on monthly returns running from January 2019 through December 2023 on the market as a whole and on six individual stocks: AT&T, Exxon-Mobil, JetBlue, Nvidia, PepsiCo, and Tesla. Question 1. Use these data to estimate the CAPM betas for each of the six individual stocks. There are at least three ways of doing this. Choose whichever is easiest or most convenient for you. One way is to load the data into a statistics or econometrics software package like Stata or R, and regress each individual stock return on a constant and the market return. The slope coefficient from this regression equals the CAPM beta: the covariance between the dependent variable (the individual stock return) and the independent variable (the market return) divided by the variance of the independent variable (the market return). It is also possible to estimate the slope coefficient from the regression described above using Google Sheets. To do this, download the Excel spreadsheet and open it instead with Google Sheets. Then, to estimate the beta for AT&T’s stock, use the command “=slope(C12:C71,B12:B71)”. For the other five stocks, keep the range of the independent variable B12:B71 as above but change the range of the dependent variable to match the columns containing data for the other stock returns. A third way is to use Excel, Google Sheets, or some other computer program to calculate the covariance between the individual stock return and the market return and the variance of the market return, then to divide the covariance by the variance. Now you know how to estimate CAPM betas! 2.2 CAPM Betas and Expected Returns Question 2. Use the CAPM betas that you estimated above to determine the expected return on each of the six individual stocks. To do this, you also need to estimate the risk-free rate and the expected return on the market portfolio. For this task, it is useful to find data on a slightly longer sample of data since stock returns, in particular, have been unusually high over the past five years alone. The annual data set mentioned above contains data on annual returns, running all the way back to 1927 and extending through 2023. This period includes the Great Depression of 1929 through 1933 and the era of very high inflation during the 1970s. Therefore, it may be too long to reliably predict stock returns in the near future. Instead, let’s use the annual data but focus on just the 24 years from 2000 through 2023. Over that period, the average return on the stock market has been 8.96 percent – approximately 9 percent – which suggests setting ❊[r˜M] = 9 in the CAPM formula. Meanwhile, although the Federal Reserve is presently targeting interest rates in a range between 5.25 and 5.50 percent, most financial market participants expect that the Fed will begin reducing interest rates later this year. Based on these considerations, let’s take rf = 5 as our best estimate for the risk-free rate in the CAPM formula. Now, you are ready to compute the CAPM estimates of the expected return on each of the six stocks. 2.3 Value Stocks and the CAPM Many successful investors have learned that it is possible to “beat the market,” that is, earn average returns above those provided by the market as a whole, by investing in “value stocks,” that is, shares in old-fashioned companies that most other investors ignore and whose prices are beaten down and by avoiding “growth stocks,” that is, shares in newer and more popular companies whose prices have already been bid up. Warren Buffett, most famously, made his fortune partly through “value investing,” but many others have profited from the strategy as well. The superior performance of value stocks over growth stocks can be quantified using the “HML” measure developed by Eugene Fama and Kenneth French and described in more detail below. According to this measure, value stocks provided annual returns that were, on average, 5.9 percentage points higher than returns on growth stocks over a long period extending from 1927 through 2006. Interestingly, growth stocks have done much better recently: from 2007 through 2023, they have returned, on average, 3.4 percentage points more than value stocks. Even after accounting for this recent reversal, over the full period from 1927 through 2023, the annual return on value stocks remains 4.3 percentage points higher, on average, than the return on growth stocks. Financial economists will always be quick to point out that higher average or expected returns on value compared to growth stocks do not necessarily violate the implications of the CAPM. Suppose, in particular, that value stocks have higher CAPM betas than growth stocks. Then, the CAPM predicts that value stocks will have higher expected returns as well. The interpretation of Warren Buffett’s success would then be: he earned higher returns, but only because he was willing to take on more aggregate risk. It turns out, though, that two famous research articles, one by Barr Rosenberg, Kenneth Reid, and Ronald Lanstein (“Persuasive Evidence of Market Inefficiency,” Journal of Portfolio Management, Spring 1985) and the other by Eugene Fama and Kenneth French (“Common Risk Factors in the Returns on Stocks and Bonds,” Journal of Financial Economics, February 1993), find that higher average returns on value stocks compared to growth do violate the CAPM. That is, value stocks offer higher average returns than growth stocks, even after accounting for differences in their CAPM betas. By answering this question, you will see whether or not the earlier results presented by Rosenberg, Reid, and Lanstein and by Fama and French continue to hold in the longer set of annual data, running from 1927 through 2023, mentioned above. This data set runs well beyond those used in the original studies. This exercise is both interesting and important because, as noted above, value investing strategies have performed quite poorly, in recent years, while growth stocks like Apple, Facebook, and Nvidia have provided far superior returns. If you include this recent data in your sample, will it still appear that value stocks outperform. growth stocks on average? Are the differences in expected returns still larger than what is predicted by the CAPM? And are the deviations from the CAPM’s predictions still “statistically significant?” These are the broader issues you will address here. Rosenberg, Reid, and Lanstein and Fama and French distinguish value from growth stocks by comparing each company’s “book value” to its “market value.” Book value measures the accounting value of the firm’s assets per share. Market value is just the market price of each share of stock. According to Rosenberg and Fama and French, value stocks are those with high book compared to market values, and growth stocks are those with low book-to-market values. Let r˜H be the random return on a portfolio of high book-to-market value stocks, and let r˜L be the random return on a portfolio of low book-to-market growth stocks. As usual, let r˜M be the random return on the market portfolio, and let rf be the risk-free rate. Then, as we know, the CAPM implies E[r˜H] = rf + βH(E[r˜M] − rf ) (1-1) E[r˜L] = rf + βL(E[r˜M] − rf ) (1-2) where βH and βL are the CAPM betas on the portfolios of value and growth stocks. To concentrate specifically on the returns from a value investing strategy, Fama and French define an HML (“high-minus-low”) portfolio that takes long positions in value stocks and short positions of equal value in growth stocks. The random return on this HML portfolio is therefore r˜HML = r˜H − r˜L (1-3) and, according to the CAPM E[r˜HML] = (βH − βL)(E[r˜M] − rf ) (1-4) This implication of (1-4) will form. the basis of our statistical test of the CAPM and, specifically, of the continued profitability of the value investing strategy embodied in Fama and French’s HML portfolio. Consider, in particular, a regression of the return on the HML portfolio on a constant and the difference between the market return and the risk-free rate: r˜HML,t = α + β(r˜M,t − rf,t) + ϵt (1-5) We can see that the slope coefficient β from the regression equation (1-5) provides an estimate of the HML portfolio’s CAPM beta. More importantly for our purposes, (1-4) implies that according to the CAPM, the intercept term α in the regression equation (1-5) should equal zero. We can test the CAPM’s implications, therefore, by seeing whether the estimated value of α in (1-5) is statistically different from zero. The annual data set mentioned above contains data on the HML return rHML,t and the excess return on the market that you can use to run this statistical test. Since, for this question, we are interested in interpreting the past as opposed to predicting the future, it makes sense to use the full range of annual data running from 1927 through 2023. Question 3. Use these data to estimate the regression in (1-5). Then, if you are interested or have learned a bit of econometrics, think about the following optional questions. Question 4 (optional). Use the t-statistic to test the null hypothesis, implied by the CAPM, that the intercept is equal to zero. Discuss your findings. Question 5 (optional). Check whether your answer to the above question is robust or not by restricting the sample to different time periods. Discuss your findings.
EE1002 Principles of Electrical Engineering (2024/25A) Lab C – RC Circuit Safety Precautions • Refer to the departmental and university safety regulations. Report to the lab demonstrators immediately in case of any irregularities. • In the rare event of electric shock, one should be removed from the source and the current should be shut down immediately. • Before touching any circuit elements, ensure that it is not connected to high voltages. We only need to deal with voltages below 20 V in this course. • When using the DC power supply, dial the voltages to zero before switching it and before connecting the circuit. Double check your circuit before dialing up the voltage from zero. • Electrolytic capacitors CANNOT be connected to a reverse voltage. Acknowledgment – This version is largely based on the lab reports before this semester. I. OBJECTIVES 1. To measure time-varying voltages using an analog oscilloscope. 2. To study the amplitude response of an RC circuit as a function of frequency. 3. To study the phase response of an RC circuit as a function of frequency. II. EQUIPMENT 1. Signal generator SG (Model: ) 2. Real-time Analog Oscilloscope OSC (Model: ) 3. Digital Multimeter (Model: ________________________________) 4. BNC cable 5. Solderless breadboard 6. Components: Resistor R=1 kΩ; Capacitor C= 0.l μF. Check: Using the multimeter to verify the values of R= and C = . The correct mode is needed for measuring C. III. BACKGROUND An AC voltage is a sinusoid with a period T. For RC circuit, the characteristic time is RC according to Chapter 8. When the AC voltage drives the RC circuit, the behavior depends on the comparison of T and RC. • If T >> RC, then the capacitor behaves as an open-circuit. • If T
ECON10151 Lecture 4 Managing Data with Excel Functions Oct 2024 Learning Outcomes • Be able to effectively retrieve data from a dataset using VLOOKUP, INDEX, and MATCH functions, and apply them to large datasets. • Understand the differences and use cases of VLOOKUP versus INDEX and MATCH, enabling them to choose the appropriate function based on specific data retrieval needs. Introduction Excel offers a wide range of powerful functions that can help you manage, analyse, and extract valuable insights from data. This week, we’ll focus on three key functions that are essential for working with data effec- tively: VLOOKUP, MATCH, and INDEX. These functions will enable you to quickly find specific information, locatedata within a table, and retrieve values from different parts of your dataset. 1 VLOOKUP In this section, we will explore the syntax of VLOOKUP and will break down the arguments so that you can understand how they work. 1.1 VLOOKUP Syntax The VLOOKUP function searches for a value in the first column of a table and returns a value in the same row from another column. Syntax: =VLOOKUP(lookup value, table array, col index num, [range lookup]) Arguments: • lookup value: The value you want to search for in the first column of the table. • table array: The range of cells that contains the data. The first column of this range is where the lookup value will be searched. • col index num: The column number (starting from 1) from which you want to retrieve the value. • [range lookup] : An optional argument. Use TRUE for an approximate match or FALSE for an exact match. FALSE is recommended for most cases to ensure accurate results. 1.2 Practice with VLOOKUP Instructions In this exercise, you will practice using the VLOOKUP function in Excel to retrieve specific data from a table. You will be working with a dataset that contains information about students, their departments, academic year, and GPA. Follow the tasks below to complete the exercise. Dataset The dataset contains the following columns: • Student ID: Unique identifier for each student. • Name: Name of the student. • Department: The department the student belongs to. • Year: The academic year of the student. • GPA: The student’s Grade Point Average. Task 1: Find GPA for Given Students You are provided with the names of two students: • Alice Smith • George Patel Your task is to use the VLOOKUP function to find their GPAs from the dataset. Follow these steps: 1. Open Excel L4 Data and work on the worksheet named as VLOOKUP. 2. In cells B15 and B16, use the VLOOKUP function to find the GPA for each of the two students. 3. Syntax of VLOOKUP: =VLOOKUP(lookup value, table array, col index num, [range lookup]) 4. Setup • lookup value: The value you want to search for in the first column of the table. - Set it to the student’s name. • table array: The range of cells that contains the data. The first column of this range is where the lookup value will be searched. - Select the data range covering the columns from Student Name to GPA. • col index num: The column number (starting from 1) from which you want to retrieve the value. - It is the GPA column, which is the 4th column in the range. • range lookup: An optional argument. Use TRUE for an approximate match or FALSE for an exact match. - We set it to FALSE to ensure an exact match is found. Remember: Make sure the lookup value is in the first column of the table array. Therefore, when you select data for the table array, ensure that the student names are in the first column of this array. The GPA for Alice Smith: = VLOOKUP(A15, $B$2:$E$11, 4, FALSE) The GPA for George Patel: = VLOOKUP(A16, $B$2:$E$11, 4, FALSE) 5. Graphical illustration of the formula: Figure 1: Task 1 VLOOKUP Example 6. Report the GPAs for Alice Smith and George Patel. You should obtain the following results once you have entered the formula. Figure 2: Task 1 Results Task 2: Check if Student Name Exists in the Dataset You are given the following names: • Julia Fernandez • Michael Green Your task is to use the VLOOKUP function to check if these names exist in the dataset. Follow these steps: 1. Think: How to use VLOOKUP If the name exists, return the corresponding Name from the list. If not, the function should return an error (such as #N/A). 2. Syntax of VLOOKUP: =VLOOKUP(lookup value, table array, col index num, FALSE) 3. Setup • lookup value: The value you want to search for in the first column of the table. - Set it to the student’s name. • table array: The range of cells that contains the data. The first column of this range is where the lookup value will be searched. - Define table array as the data range covering the single column of Student Name. • col index num: The column number (starting from 1) from which you want to retrieve the value. - Assign col index num to the first column, which is the only column in the range. • range lookup: An optional argument. Use TRUE for an approximate match or FALSE for an exact match. - Set range lookup to FALSE to ensure that an exact match is found. Remember: Make sure the lookup value is in the first column of the table array. Therefore, when you select data for the table array, ensure that the student names are in the first column of this array. Julia Fernandez: = VLOOKUP(A20,$B$2:$B$11,1,FALSE) Michael Green: = VLOOKUP(A21,$B$2:$B$11,1,FALSE) 4. Graphical illustration of the formula: Figure 3: Task 2 VLOOKUP Example 5. Report whether each of the two names is found in the dataset. You should obtain the following results once you have entered the formula. Figure 4: Task 2 Results This suggests that Julia Fernandez is included in the dataset; however, Michael Green is not on the list, as it returns an error (#N/A )in the cell. 2 INDEX and MATCH In this section, we will briefly explore the syntax of the INDEX and MATCH functions. The INDEX function returns a value based on specified row and column numbers within a given array, while the MATCH function finds the position of a value in a row or column. We will break down their arguments to help you understand how each function works. INDEX The INDEX function returns the value in a specified cell. You need to know the row and column numbers of the cell within an array so that Excel can locate its position. Once identified, the function returns the value contained in that cell. Syntax: =INDEX(array, row num, [column num]) Arguments: • array: The range of cells that contains the data from which you want to retrieve a value. • row num: The row number in the array from which you want to retrieve a value. • [column num] : The optional column number in the array. If omitted, the function will return the value from the first column. MATCH The MATCH function searches for a specified value in a specific column or a row and returns the relative position of that value. Syntax: =MATCH(lookup value, lookup array, [match type]) Arguments: • lookup value: The value you want to search for in the array. • lookup array: The range of cells that contains the data you want to search. The lookup array here can only be a single column or a single row. • [match type] : An optional argument. It specifies how Excel should match the lookup value. Use 1 for the largest valueless than or equal to the lookup value, 0 for an exact match, or -1 for the smallest value greater than or equal to the lookup value. For most scenarios, 0 is preferred to ensure an exact match. 2.1 Practice with INDEX and MATCH Task 1: Obtain the GPA of the Student with ID 33104 Using INDEX and MATCH Manually finding a student’s GPA would involve identifying the correct row where the Student ID appears and then locating the GPA in the corresponding column. For small datasets, this is simple, but as datasets grow larger, manually finding this information becomes prone to error and time-consuming. With Excel’s INDEX and MATCH functions, we can automate this task and ensure accuracy. Thus, in this task, we can use MATCH to find out the row number and the column number. Then, INDEX can return the value of GPA based on the row number of Student ID and the column number of GPA. Your objective is to find the GPA of the student with the Student ID: 33104. To achieve this goal, we can follow these steps: 1. Use the MATCH function to find the row number where the Student ID 33104 is located. • (Worksheet: MATCH and INDEX) Begin with the cell I7 and type MATCH formula in the cell. • Syntax of MATCH: =MATCH(lookup value, lookup array, [match type]). • Setup 。lookup value: The value you want to search for in the array. - This case, it is 33104 (the Student ID you’re looking for). 。lookup array: The range of cells that contains the data you want to search. The lookup array here can only be a single column or a single row. - We select the column of Student IDs (column A in the dataset). 。 [match type] should be set to 0 for an exact match. The row number of Student ID 33104: = MATCH(H7, A2:A11, 0) • Graphical illustration of the formula: Figure 5: Task 1 MATCH Example: row no. 2. Use the MATCH function to find the column number where the GPA is located. • Begin with the cell I11 and type MATCH formula in the cell. • Syntax of MATCH: =MATCH(lookup value, lookup array, [match type]). • Setup 。lookup value: The value you want to search for in the array. - It is GPA (the header you are looking for in the row, including all headers). 。lookup array: The range of cells that contains the data you want to search. The lookup array here can only be a single column or a single row. - We select the row of headers (Row 1 in the dataset). 。 [match type] should be set to 0 for an exact match. The column number of GPA: = MATCH(H11,A1:E1,0) • Graphical illustration of the formula Figure 6: Task 1 MATCH Example: column no. 3. Use the INDEX function to return the GPA of the student with ID 33104 We can fill in the INDEX function based on the row number and the column number found using the MATCH function. • Begin with the cell I17 and type INDEX formula in the cell. • Syntax of INDEX: =INDEX(array, row num, [column num]) • Setup 。array contains all of the values in this student information data set. 。row num corresponds to the row number of the student ID 33104. 。col num corresponds to the column number where GPA is located. The GPA of the student with ID 33104: = INDEX(A1:E11,I7,I11) • Graphical illustration of the formula: Figure 7: Task1 INDEX Example
BUSI4528-E1 A LEVEL 4 MODULE, AUTUMN SEMESTER 2019-2020 QUANTITATIVE RESEARCH METHODS FOR FINANCE AND INVESTMENT 1. a) In a regression of the U.S. non-farm mortgage debt outstanding on two variables from 1980 to 1995, the following regression results were obtained using Stata: Debt: non-farm mortgage debt outstanding in billion $ in the U.S. Income: personal income in billion $ in the U.S. Cost: new home mortgage cost in % (i) Write down the regression model. [10 marks] (ii) Interpret the meaning and significance of each coefficient including the intercept. [20 marks] (iii) What is the goodness-of-fit of a regression model and what is the F-test for? Comment on the goodness-of-fit and the F-test results of the above model. [25 marks] (iv) Explain the term collinearity. Discuss its consequences in model estimation and explain how to detect it. [20 marks] b) Explain how graphical analysis of time series may help to identify nonstationary variables. [25 marks] Total [100 marks] 2. a) A sample of 100 workers found the average overtime hours worked in the previous week was 7.8, with standard deviation 4.1 hours. Test the hypothesis that the average overtime hours for all workers is 6.5 hours or less. Use 5% as significance level. (i) Describe step-by-step the procedure of testing the above hypothesis and state the conclusion. [30 marks] (ii) What is p-value? Use the p-value method to test the above hypothesis. [20 marks] b) Using standard mathematical notation, explain whether the following nonstationary time series models are characterized by deterministic or stochastic trends : (i) linear trend model [10 marks] (ii) random walk [10 marks] (iii) random walk with drift [10 marks] c) What is meant by ‘spurious regression’? Explain why empirical analysis should be cautious of it. [20 marks] Total [100 marks] 3. a) Answer the following questions about panel data modelling. (i) Compare and contrast the pooled OLS and fixed effects model in panel data estimation. [20 marks] (ii) Explain the difference between the fixed effects model and the random effects model and how to decide which model is appropriate? [30 marks] b) Consider the following time series model with serially correlated error term: yt = α + βxt + εt , with εt = P1 εt−1 + vt where var(vt ) = σv(2) , and Cov (vt, vs ) = 0 for t ≠ S Show how one could construct a feasible GLS estimator for the parameters α and β . Discuss the merits of doing so. [50 marks] Total [100 marks] 4. a) Answer the following questions about heteroscedasticity. (i) Describe what heteroscedasticity is and the consequences of the presence of heteroscedasticity in linear regression. [20 marks] (ii) Explain how might the presence of heteroscedasticity be detected and what are the possible solutions to address this issue. [30 marks] b) Outline the setup of Probit and Logit models for binary choice data. [50 marks] Total [100 marks] 5. a) What does BLUE estimator mean and what are the assumptions to obtain BLUE estimators in a simple linear regression model: y = β1 + β2x + e ? [25 marks] b) Outline the Dickey-Fuller (DF) test for the null hypothesis of the presence of a unit root in time series. [25 marks] c) Explain how you could test the null hypothesis of no cointegration between two time series variables. [50 marks] Total [100 marks]
COMM1023 Fundamentals of Communication Final Essay (25%) Deadline: 27 December 2024 (Friday), 9.00a.m. (upload to iSpace, late submissions will be deducted 10% per day late) Length: 900-1000 words (excluding References) Draft Essay Due Date (5%): 2 December 2024 (Monday), 9.00a.m. (upload to iSpace). Feedback on draft to be given in Week 14 (Dec 9-13) during seminars. Answer one of the following questions: 1. In what ways has digital media reshaped patterns of media consumption? Discuss two specific examples of these transformations and critically examine their broader social or cultural implications. 2. Examine the challenges faced by media producers in the digital era. Discuss issues such as copyright concerns, shifting audience behaviors, and the influence of social media on media production. 3. In the digital age, we are not just sitting there passively receiving. How do audiences actively shape the meaning of media texts? Use your own examples from areas such as social media or fan communities to discuss how audience interpretations can challenge or reinforce the creator's intended message. 4. How does social media influence political beliefs among young adults? Explore how social media platforms shape or reinforce political views and opinions among young people. Students can examine theories such as the agenda-setting function of social media, the spiral of silence, and the third-person effect, providing examples from recent political events to illustrate how social media impacts audience perception and behavior. 5. Choose a specific example where AI-Generated Content (AIGC) was used in a news story or media production. Analyse the ethical challenges posed by this case from perspectives such as authenticity and public trust, media professional responsibilities, copyright issues, and social bias. How did these challenges impact the relationship between the audience, media practitioners, and the media content itself? 6. In the digital age, we don’t just consume images passively; visual culture plays a role in shaping who we are. Discuss how visual media (like films, TV, or social media) contributes to personal and collective identity. For instance, consider how movie characters or online personas might influence people’s sense of self or values. Use your own examples to explore this influence. 7. How is virtual reality transforming consumer experiences in retail and entertainment? Explore how VR technology is utilized in retail and entertainment to enhance customer engagement and satisfaction. Students can discuss interactive design principles and analyze real-world examples, such as virtual try- ons in fashion and immersive experiences in movie theaters and gaming. 8. What is the role of nonverbal communication in building trust during live-stream shopping and TV sales? Explore how nonverbal cues—such as body language, eye contact, and tone—affect consumer trust in live-streaming sales and TV shopping. Students can apply theories of interpersonal communication to discuss why nonverbal communication is crucial in these scenarios, supported by examples from popular live-stream platforms or TV sales shows. 9. How have recent technological developments influenced China’s ability to “tell a Chinese story well” on the international stage? Analyse how advancements in digital media have impacted the effectiveness of Chinese storytelling campaigns. Use a specific case to illustrate how technology has enhanced or hindered the ability to convey cultural narratives to a global audience. Instructions: l The assignment needs to be written formally with paragraphs, an introduction and conclusion, and a References list. Use APA referencing style. consistently. l Do not write the essay using bullet points. l Your essay needs to have a References list. Reminders: Penalties for academic dishonesty should be executed in the following manners: l A student who is found to have committed an act of academic dishonesty in respect of any part of a course-based assessment such as plagiarism in written assignments, submission of material(s) for assessment which is not the student’s own work, the use of fabricated or copied data for assessment, shall receive zero marks for the part found plagiarized. l For more serious or repeated cases, the student concerned shall be given an F grade for the whole course and disciplinary action may be sought from the Student Disciplinary Committee. l Any student found to have committed academic dishonesty shall be excluded from participating in the end-of-semester teaching and learning evaluation for the course concerned. l ChatGPT and other generative AI tools may be used for brainstorming and proofreading, but not for writing this assignment. Final Essay Rubrics % 1 2 3 4 5 Use of examples 35 No examples Poor examples; most not relevant to the topic Examples often inadequate to support argument Good examples; some examples are irrelevant to the topic Excellent examples that illustrate the topic very well Depth of analysis 35 No analysis Minimal analysis that often rests entirely on description Adequate analysis that does not probe beneath the surface of the topic Often deep analysis that partially includes the student’s own input Very deep analysis that explores multiple aspects from the student’s own perspective Inclusion of Sources and Citations 20 No materials referenced Poor understanding shown; very few readings mentioned; inconsistent with APA style Comprehension often unclear; narrow range of readings discussed; many errors following APA style Comprehension fair; some slight misunderstandings; wide range discussed; often follows APA style Shows excellent comprehension with a wide range of materials; follows APA style Structure 10 Incoherent Very poorly structured; hard to follow; intro and/or conclusion missing Adequate structure although unclear in places such as intro and conclusion Good structure; Any lack of clarity does not greatly impede comprehension; intro and conclusion fair Clear structure; easy to follow and comprehend; includes complete intro and conclusion
Assignment 9 EMATM0061: Statistical Computing and Empirical Methods, TB1, 2024 Introduction This is the 9th assignment for Statistical Computing and Empirical Methods. This assignment is mainly based on Lectures 25, 26, 27 (see the Blackboards). Please note that you don’t need to submit this assignment. Load the tidyverse package: library(tidyverse) Some questions require the “glmnet” and “QSARdata” packages. If they are not already installed on your computer, please install them using “install.packages()” first. 1. Linear discriminant analysis (Q1) Describe the probabilistic model that underpins linear discriminant analysis. (Q2) In this question, we will train a linear discriminant analysis model to carry out the classification task to predict whether a hawk belongs to either the “Sharp-shinned” (SS) or the “Cooper’s” (CH) species of hawks, based on a four dimensional feature vector containing the weight, and the lengths of the wing, the tail and the hallux, which are generated by the following code. library(Stat2Data) data(Hawks) hawks_total % select( Weight, Wing, Hallux, Tail, Species) %>% filter(Species=='SS' | Species =='CH') %>% drop_na() %>% mutate(Species=as.numeric(Species=='SS')) Assume that we have the following train-test split of our dataset. num_total % nrow() # number of penguin data num_train
Coursework 3 In this coursework, you are required to write several Python functions, by filling in code into the template below. Submit your Python script. via upload on Blackboard before the deadline on Friday, 13th December 2024 at 1pm. I suggest aiming to submit at least one hour earlier, to avoid any last-minute computer problems. Working independently As with all assessed work in this unit, you must complete this coursework independently on your own. You must not take code from elsewhere, even if it is referenced. You are however allowed to use the lecture notes and exercise solutions freely, and the lecture notes contain all that is required to solve the problems. You are not allowed to ask others for help, and in particular, you are not allowed to send, give, or receive Python code to/from classmates and others. See the University Guidelines for Academic Malpractice. Instructions 1. Copy the code out of the template below and save it as a .py file in Spyder (or another Python editor of your choice). 2. Add your name, university ID number and university email address in the docstring at top of the file, where indicated 3. Write code to replace the pass statements in the functions initial_state, parse_move, validate_move, apply_move, game_won for questions 1–5. For questions 1–5, do not alter the existing play_game function. 4. For questions 6–8, modify only the parse_move and play_game functions as requested. 5. Do not alter the names or parameters of any functions. Do not create any further functions with the same names. Ensure that these functions can be called with the parameters precisely as specified, and that they return (not print) values of the correct data types. 6. Submit your work on Blackboard as a .py Python file. Do not submit a screenshot, PDF, Word document, iPython notebook, or file in any other format. Aspects of this coursework will be marked automatically and failure to follow the problem description or any of the instructions above will result in loss of marks. To check that your code is working correctly, you may wish to add some of your own tests in a new function – these will not be marked. If you wish, you can also add other functions to the code, and call them from the required functions. Make sure all code (other than module import statements) is within a function. Do not create any further functions with the same name as any of the required functions. . Do not use the input function anywhere in your code. The only use of input allowed is my existing line of code in the play_game function. . Make sure your functions return the value they should return, not just print the value to screen. As this is part of the course assessment, we will not be able to help you solving these problems. If you are unsure what any question is asking for, please ask on the Blackboard Discussion Forum. If you provided a valid email address in the docstring at the beginning of your .py file, you will receive a feedback report with your score for each function. Template code The template that you should use for your coursework is below. Two functions are provided: . display_state is a function that displays the state of the game on the screen, using fancy colours! . play_game is a pre-written basic framework for the game. You must not modify this function for questions 1–5, but it is modified in questions 6–8. """ MATH20621 - Coursework 3 Student name: add your name Student id: add your id number Student mail: [email protected] """ def display_state(s, *, clear=False): """ Display the state s If 'clear' is set to True, erase previous displayed states """ def colored(r, g, b, text): rb,gb,bb=(r+2)/3,(g+2)/3,(b+2)/3 rd,gd,bd=(r)/1.5,(g)/1.5,(b)/1.5 return f"33[38;2;{int(rb*255)};{int(gb*255)};{int(bb*255)}m33[48;2;{int(rd*255)};{int(gd*255)};{int(bd*255)}m{text}33[0m" def inverse(text): rb,gb,bb=.2,.2,.2 rd,gd,bd=.8,.8,.8 return f"33[38;2;{int(rb*255)};{int(gb*255)};{int(bb*255)}m33[48;2;{int(rd*255)};{int(gd*255)};{int(bd*255)}m{text}33[0m" colours = [(1.0, 0.349, 0.369), (1.0, 0.573, 0.298), (1.0, 0.792, 0.227), (0.773, 0.792, 0.188), (0.541, 0.788, 0.149), (0.322, 0.651, 0.459), (0.098, 0.509, 0.769), (0.259, 0.404, 0.675), (0.416, 0.298, 0.576)] n_columns = len(s['stacks']) if clear: print(chr(27) + "[2J") print(' ') row = 0 numrows = max(len(stack) for stack in s['stacks']) for row in range(numrows-1,-1,-1): for i in range(n_columns): num_in_col = len(s['stacks'][i]) if num_in_col > row: val = s['stacks'][i][row] if num_in_col == row+1 and s['blocked'][i]: print(inverse(' '+str(val)+' '),end=' ') else: if s['complete'][i]: print(colored(*colours[val-1],' '),end=' ') else: print(colored(*colours[val-1],' '+str(val)+' '),end=' ') else: print(' ',end='') print() print(' A B C D E F') # Q1 def initial_state(): pass # Q2 def parse_move(input_str): pass # Q3 def validate_move(state, move): pass # Q4 def apply_move(state, move): pass # Q5 def game_won(state): pass # For questions 1-5, DO NOT edit the play_game function. # For the tasks in questions 1-5 initial_state, parse_move, # validate_move, apply_move, and game_won must work with the # the unmodified play_game function. # For questions 6, 7 and 8, you should modify the play_game # function def play_game(): # When we start the game, board = initial_state() try: while True: # Display the current game state display_state(board, clear=False) # Read input from the user. # (Do not alter this line, even in questions 6, 7, 8.) move_str = input() # Parse the text typed by the user and convert it to a move move = parse_move(move_str) # If the move was valid... if validate_move(board, move): apply_move(board, move) # ... alter the board # If we've won, end the game if game_won(board): break except KeyboardInterrupt: # If the user presses Ctrl-C, quit pass play_game() Solitaire This coursework implements a game of solitaire. Solitaire, or Patience, is a name given to a single-player game, usually a game played with a pack of cards. The game originated in Europe in around 1800, and numerous variations have been developed since. During this coursework, you will write Python program to simulate a particular variation of solitaire. The game works as follows. When played as a tabletop game, we start with a standard 52-card deck, but only the numerical cards 1, 2, 3, 4, 5, 6, 7, 8, 9 are dealt – the court cards (King, Queen Jack) are omitted. The suit of the cards ( , , , ) plays no role in the game. As a result, there are 36 cards in play, four copies of each of the numbers 1–9. We’ll refer to the ace as 1, rather than A. These cards are shu!ed and dealt into six stacks, which we’ll name A through F, each containing six cards, for example: The aim of the game is to rearrange these cards into four complete stacks of nine ordered cards. Here, ‘ordered’ means in decreasing order going down the stack, i.e. Here, the complete stacks are A, B, D and F, and stacks C and E are empty, but which are full and empty does not matter: the game is complete once there are four complete stacks. The challenge of the game is, of course, that only certain moves are permitted. Moving single cards The basic move in this solitaire varient is to move a card from the top of one stack, and place it onto another stack onto a number that is one larger. For example, in the following game, we could take the 1 card from stack E and move it onto the 2 card on stack C. This is one of several moves we could have made: we could alternatively have moved the 2 in stack C onto the 3 in stack A, the 3 in stack A onto the 4 in stack B, or the 7 in stack D onto the 8 of stack F. Moving multiple cards We can move more than one of the top cards on a stack at once, so long as those cards are ordered. For example, after our first move there is a pair of ordered cards at the top of stack C: Just as before, we can move this pair to another stack if the top number in the destination stack is one larger than the bottom card of those to be moved. In our game, the only stack that satisfies this is stack A, and we can move two cards from stack C to stack A: You may have noticed that there is another pair of ordered cards, an 8 and a 9, at the top of stack F. We cannot move this pair currently, as there is nowhere for it to go. The rule for moving a 9 card (or multiple cards with 9 the largest) is that a 9 can only move into an empty stack. We can however move the new stack of 1, 2, 3 formed on stack A onto stack B: Our available moves are now a bit limited. While we can move the single 8 on stack F onto stack E, that doesn’t really help us progress, as it only reveals a 9. Perhaps the best move is to move the 7 on stack D onto stack A: At this point, there are still moves we can make, but it’s di"cult to see how we can make enough cards to completely re-order them into four complete stacks as required. However, we are allowed to break the rules established above, in a very specific way. Blocking moves A single card at the top of a stack can be moved onto another stack, even if it is not one less than the number at the top of the destination stack. However, in that case, the moved card blocks the destination stack, here indicated with a black card. No further cards can be added to the destination stack. The only way to unblock the stack is to move the single blocking card at the top of the stack onto a valid location – that is, onto an empty stack, or onto a stack whose top card is one greater than the card being moved. So, we can move the 1 from stack C to stack E. This blocks stack E, really opens things up. We move the 3 from stack D to stack C, then the 2 from stack D to stack C. Then, we can then move the blocking 1 from stack E onto the 2 on the top of stack C, thus unblocking stack E, as follows: We’ll now take a succession of steps: · Move the top four cards from stack B (1, 2, 3, 4) onto stack D · Move the top five cards from stack D (1, 2, 3, 4, 5) onto stack B · Move the top six cards from stack B (1, 2, 3, 4, 5, 6) onto stack A Move the top card from stack D, now a 1, onto stack F. This blocks stack F. Move the top card from stack D, now a 8, onto stack E. Our stacks now look like Making a complete stack We’ve now got a complete run of numbers of 1, 2, 3, 4, 5, 6, 7, 8, 9 at the top of stack A. Moving these to the empty stack D gives us the first complete stack that we are looking for. Here this made by moving all nine cards to an empty stack all at once, but a complete stack can be formed over more than one move too. For example, we could have made the complete stack by first moving the top two cards of stack E (9 and 8) to stack D, then the top seven cards of stack A to stack D. Either way, once a complete stack is formed, the cards on it are turned over, and no cards can added to or removed from that stack for the rest of the game. (This is indicated here by the numbers begin removed from the cards.) We now continue the game in the same way, except without being able to use stack D. Can you see how in seven further moves, we could both complete a second stack and both unblock stack F? In terms of strategy, it is not always best to complete stacks as soon as possible, as this prevents that stack from being used again, constraining what is possible in future moves. Python implementation The game state The most important part of this game is the representation of the game state — that is, which cards are in which stacks, which stacks are blocked, and which are complete. We represent the board state with a Python dictionary, (say, s), with three keys: 1. s['blocked'] is a list of six boolean values, corresponding to the six columns A–F. The value is True if the column is blocked by a card, or False if it is not. 2. s['complete'] is a list of six boolean values, corresponding to the six columns A–F. The value is True if the column is completed, or False if it is not. 3. s['stacks'] is a list of six lists of integers, corresponding to the cards in each stack. The lists are ordered from bottom up, so for example s['stacks'][1][0] is the bottom card on stack B. could be created in Python with the statement: s = { 'blocked' : [ False , False , False , False , False , True], 'complete' : [ False , False , False , True , False , False], 'stacks' : [[2 , 7 , 4], [1 , 6 , 5 , 3], [7 , 8 , 9 , 4 , 3 , 2 , 1], [9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1], [5 , 7 , 6 , 4 , 9 , 8], [1 , 3 , 5 , 2 , 9 , 8 , 1]]} For any one column, blocked and complete should never both be True. An empty stack is indicated by the corresponding element of s['stacks'] being an empty list []. Note that even though the cards in the completed stack are not shown, the representation in 'stacks' shows the nine cards in order. Thus, at all times, the lists in 'stacks' should together contain 36 elements, four of each of the digits. Describing a move The other key part of the game is the idea of a move. A move is uniquely described by the source stack, the destination stack, and the number of cards to be moved. We’ll represent a move as a tuple of three integers, The stacks are numbered from the left, starting with zero, so stack A is 0, stack B is 1 and so on. For example, the move (0, 4, 3) represents a move of three cards from stack A onto stack E, while a move (1, 2, 1) represents a move of one card from stack B onto stack C. The assessed questions: This coursework is worth 70 marks, and 70% of the course overall. 30 marks are allocated for the correctness of the functions defined in problems 1–5. These will be tested in an automated way, as in the previous courseworks. 15 additional marks are allocated based on number of perfect scores for core problems 1– 5. 15 marks are allocated for problems 6–8. 10 marks are for the quality of all the code. Question 1: The initial state (6 marks) Write a function initial_state that returns a dict corresponding to the game state at the start of a new game. The cards should be randomly shu!ed, allocated six to each stack, and no stack should be marked complete or blocked. Question 2: Interpreting user input (6 marks) At each turn, the user is asked for their input. The user should enter a string of two letters and an integer, e.g. AB3 to indicate that they wish to move three cards from stack A onto stack B, or FD1 to indicate that they wish to move one card from stack F onto stack D. Write a function parse_move(input_str) which takes a string of this form. and converts it into a move tuple of the format described above, which it then returns. For example parse_move('AB3') should return the tuple (0, 1, 3). If the number of cards is omitted, make it default to one, so that parse_move('FD') returns (5, 3, 1), corresponding to the move of a single card from stack F to stack D. In this problem 2, you can assume that the string given by the user is a valid one, namely two letters in the range A–F, optionally followed by a positive integer. Question 3: Determining if a move is valid (10 marks) Write a function validate_move(state, move) which returns True if the move move can be applied to a game in state state. You can assume that the parameter state is a dictionary corresponding to a valid game state (as described above), and that the parameter move is a tuple of three integers. This function should contain all the logic for checking whether a move is valid, including all the rules described above on moving single cards, multiple cards, card ordering, blocking moves, blocked stacks and completed stacks. The function should also check for nonsensical moves (moving more cards than there are in the stack, moving to a nonexistent stack, etc.) Question 4: Moving the cards (6 marks) Write a function apply_move(state, move) which takes a valid game state state and a move tuple move. This function does not return anything, but modifies in-place the state parameter passed to it to apply the move described by the move tuple. You can assume that state is a valid game state and that move is a valid move that could be played in this state. This function should update the blocked and complete fields of the game state state, as well as the stacks. Question 5: Detecting a win (2 marks) Write a function game_won(state) which takes a valid game state and returns True if the game has been won (that is, all cards are in a completed stack) and False otherwise. The game In the template, you are given the pre-written function play_game() which uses the five functions you have just written (initial_state, parse_move, validate_move, apply_move, game_won) to simulate a game. You can now run the play_game function to play a working game. In questions 1–5, you must not change the existing play_game() function. The preceding five questions are the core questions of this coursework, together worth 30 marks. To recognise functions that are completely correct, a bonus is awarded for each question in questions 1–5 that scores full marks: 1 bonus mark is awarded if one core question scores full marks 3 bonus marks are awarded if two core questions score full marks 6 bonus marks are awarded if three core questions score full marks 10 bonus marks are awarded if four core questions score full marks 15 bonus marks are awarded if five core questions score full marks (Because an important part of the game is that all of these functions work together correctly, the bonus grows more quickly as more questions score full marks.) There are then three additional questions (6–8, worth 15 marks in total), and an assessment of code quality (10 marks), whose marks simply add to the 45 available in questions 1–5 to make a total of 70. Question 6: Handling errors (4 marks) Modify your parse_move function from problem 2 so that raises a ValueError exception if: The string is not of the form of: two letters, optionally followed by a positive integer, or The two starting letters are outside the range A–F Modify the play_game function to catch this exception and immediately re-prompt the user for another move. As a result of these modifications, your game should now not crash, regardless of what string the user types in. Question 7: Resetting the game (2 marks) Modify the parse_move function so that if the input string is R (or r), the function returns the integer 0, rather than the move tuple. Modify the play_game function so that if parse_move returns this integer 0, then the game is reset (that is, initial_state is called and the game begins again). Question 8: Undoing moves (9 marks) Modify the parse_move function so that if the input string is U (or u), the function returns the integer -1, rather than the move tuple. Modify the play_game function so that if parse_move returns this integer -1, then the most recent move is undone. By repeatedly typing U or u), the user should be able to undo as many moves of the game as they like, until they end up back at the initial state. Ensure that the user cannot undo beyond this point Code quality (10 marks) Ten marks are available for the quality of the code that you write in questions 1–8. This will be assessed by humans reading your code, and will be based on: Clarity and precision of docstrings for each function Clarity of comments elsewhere in the code that describe what the code is doing Code quality. Code should be clear, e"cient and easy to maintain. Marks maybe lost for – Very ine"cient algorithms – Code that is unnecessarily verbose or di"cult to understand – Unnecessary duplication of code Code quality marks do not contribute to the bonus marks for questions 1–5.
DAT 500N – Prescriptive Analytics Fall 2024 Final Exam Work individually and independently on this exam Instructions This exam consists of two problems. The number of points allocated to each problem are indicated (summing up to 20 points). For full credit, you need to solve both problems using Python (using PuLP for Problem 1 and SciPy for Problem 2). If, instead, you choose to use Excel’s Solver then a 25% deduction of the full grade for that problem will be applied. You need to submit the following files on Canvas via the link pointing to this exam (under the “Assignments” section): 1. A short report (in .pdf format) that includes: o The precise mathematical formulation of your optimization models (variables, objective function, constraints) for each problem (legible, hand-written math formulation is acceptable). Provide clear definition of the decision variables Briefly state the purpose of each constraint Legible,hand-written math formulations are acceptable. o State any additional assumptions you made if the problem statement is not 100% clear about certain aspects of the problem o Answers to all case questions. Include where helpful screenshots of your Python (or Excel) results. Present the optimal solution in a clear and understandable manner. 2. Python Jupyter notebooks in .ipynb format for Problems 1 and 2, separately, with code and showing full output showing. 3. Html (or pdf) renderings of the Jupyter notebooks for Problems 1 and 2, separately, also showing full output. A full submission thus consists of 5 files. You will likely lose points if you do not adhere to the submission instructions carefully. Notes: • Html rendering of aJupyter notebook with output can be created from the File -> Download As menu in Jupyter Notebooks. For a PDF version, use the 'Print' -> 'Save as PDF' option. Google Colab may only provide a pdf rendering. • If you use the Excel option instead of Python for a given problem then an Excel spreadsheet with Solver setup and run to display the optimal solution should be provided instead of the ipynband html files. Problem 1 (12 points) This problem is adapted from a case presented in the textbook “Data, Models, and Decisions: The Fundamentals of Management Science”, by Dimitris Bertsimas and Robert M. Freund, published by Dynamic Ideas, 2004. The data Tables 1a-1c (see next page) are available electronically in the spreadsheet accompanying this exam. Delmar Inc., is a manufacturer of commercial air-conditioning systems. Facing increasing inventory and transportation costs (which is projected to amount to $1.4 million in August), you’ve been asked to see if an optimization model would help. Delmar manufactures its main product at its manufacturing plant in New Hampshire. The plant has the capacity to produce up to 50,000 units per month. The company divides up its national sales into three regions: the East Coast, West Coast, and Midwest areas of the United States. Each region is served by a regional sales distribution center, whose locations are Wilmington, Delaware (serving the East Coast); Salinas, California (serving the West Coast); and St. Louis, Missouri (serving the Midwest). Delmar operates two national distribution centers, one in Ohio (that serves the Midwest and the West Coast), and one in New Jersey (that serves the Midwest and the East Coast). Finished units are shipped from the plant in New Hampshire to the two national distribution centers (in Ohio and New Jersey), where they are stored for shipment to the three regional sales distribution centers. Delmar keeps inventory both at the two national distribution centers as well as at the three regional sales distribution centers. In order to take advantage of economies of scale in shipping, shipments are scheduled for once a month. Transportation is scheduled just in time to arrive at the national distribution centers just before they leave for the regional centers and they arrive at the regional centers just before the end of the month. Transportation lead times can be assumed negligible. The unit shipping cost from a national distribution center to a regional center is $10, regardless of the shipment size. The unit shipping cost from the manufacturing plant to a national distribution center is also $10. In addition, the fixed transportation costs (per month) of arranging for shipments are shown in Table 1a. If a shipment is not required on a given month then that fixed cost is avoided for that month. The unit inventory cost per monthat the national distribution centers in Ohio and New Jersey is $5 per unit per month, while it is $10 per unit per monthat the regional sales distribution centers. That cost is incurred on inventory level left-over at the distribution center at the end of the month. Inventory costs at the New Hampshire plant are negligible. The marketing department has provided a demand forecast for the next two months and that forecast is shown in Table 1b. This demand is withdrawn from the regional distribution centers at the end of each month. Finally, Table 1c shows the estimated inventories at each distribution center for the end of August. Your task is to develop an optimization model to determine, for each of the months of September and October, how many units to produce and how many units to ship to the distribution centers. Summarize your optimal solution in a single table and provide the associated optimal cost. Table 1a: Fixed transportation costs for the various routes at Delmar Route From To Fixed Transportation Cost [$] New Hampshire Ohio 5,000 New Hampshire New Jersey 4,000 Ohio West Coast 4,000 Ohio Midwest 3,000 New Jersey Midwest 5,000 New Jersey East Coast 3,000 Table 1b: Demand forecast for September and October Sales Region Month Forecasted Demand [units] West Coast September 20,000 Midwest October 20,000 September 15,000 October 25,000 East Coast September 25,000 October 30,000 Table 1c: Estimated inventories at the end of August Distribution Center Units National Ohio 20,000 New Jersey 10,000 Regional West Coast 2,000 Midwest 1,000 East Coast 2,000 Problem 2 (8 points) At the beginning of each semester, university bookstores around the country face high demand for course textbooks during the short period of time consisting of the first few days of the semester. Hundreds of textbook titles are sold. Consider one textbook title sold by a given bookstore. The bookstore needs to determine the selling price of a new copy and the selling price of a used copy. We consider the joint pricing problem of the new and used formats of a given textbook. To simplify, we assume that demand is deterministic; that is, once we set prices we know exactly what demand would be for each format of the textbook. Ignore integrality constraints in this problem. The Multinomial Logit (MNL) demand model is a renowned and widely used tool in both marketing and operations research, primarily for its effectiveness in analyzing consumer choice data. Currently, MNL demand models remain essential for companies, serving as a fundamental instrument in comprehending and forecasting product demand. Let us assume that the demand for the new and used copies of the textbook under consideration follows this model. In particular, the demands for the new and used copies of the textbook are given by the following expressions: where pnew is the price set for the new book and p used is the price set for the used book. The model features the exponential function where e = 2.7183 (in particular, e0 = 1.0000, e0.5 = 1.6487, e1 = 2.7183, e2 = 7.3891, etc.). For example,if the price of the new book is set to $200 and the price of the used book is set to $50 then the corresponding demands are: The cost of procuring one copy of the new book is $75 and the cost of procuring one copy of the used book is $25. The contribution margin from this textbook title is ($200 - $75) x 69 + ($50 - $25) x 113 = $11,450. Formulate an optimization problem to maximize the bookstore’s contribution margin from this textbook. The university requires that the “price ratio” (the price of the used book divided by the price of the new book) is at most 0.5. Solve the problem using SciPy. What are the optimal prices and what is the corresponding optimal contribution margin?
MECH ENG 7072 MICROCONTROLLER PROGRAMMING ASSIGNMENT 2: RAMP METER Introduction This assignment aims to build a program to control ramp meter which could significantly improve traffic in the freeway. The program is based on the C167CR-LM microcontroller, and it should include several functions: freeway car flow counting, traffic light controlling, flexibly adjusting red stop time. Therefore, this report will introduce and explain the design of the program. Design Specification The primary objective is to monitor vehicles on both the freeway and ramp. A detector will generate a digital signal whenever a vehicle passes by. The vehicle count on the freeway is utilized to determine whether it's peak or off-peak hours. Every 20 seconds (corresponding to 20 Timer4 interrupts), the program calculates the freeway overload ratio and adjusts the red light's stop duration accordingly, either increasing or decreasing it. Timer2 and Timer3 manage the control of the red, green, and yellow lights through interrupts. During peak hours, the red light's stop time is extended from 3 to 20 seconds, depending on the traffic flow. The three lights are connected to port 2. The following table outlines the inputs and outputs of the program Table 1: Summary of inputs and outputs connection I/O type Name Allocation Function Used Port Pin Digital input Freeway0 detector 2 4 detector_read_freeway Digital input Freeway1 detector 2 5 detector_read_freeway Digital input Ramp detector 2 6 detector_ramp_on Digital output Red lamp 2 1 Led_red Digital output Yellow lamp 2 2 Led_yellow Digital output Green lamp 2 3 Led_green Digital Input The system has three digital inputs. Two freeway detectors will produce a 1-second high pulse, which will be sent to pins 2.5 and 2.4.A ramp detector is used to monitor vehicles passing by. Similar to the freeway detectors, it will generate a 1-second high pulse and send it topin 2.6. Digital Output The system includes three digital outputs. The red light is connected topin 2.1, and it turns on when pin 2.1 is set to high. Similarly, pin 2.2 controls the yellow light, and pin 2.3 controls the green light. Each light will be activated when its respective pin is high.Car overload calculation: In peak time, a maximum of 20 cars are allowed to pass by in 20s(maximum=20*2=40). Therefore, the overload car is the difference between peak maximum vehicles and off-peak maximum vehicles (overload_max=40-10=30). Same as current car overload: car_count – 10. Overload proportion: Overload.proportion = (car.count − 10)/ (overload.max) Red stop time change from 3s to 20s, which means the basic time of red lamp is 3s, and additional 17s changes according to overload_proportion. Therefore: In theory, it should be one second longer for every 1.76 cars that pass. However, since the variable is defined as integer in the c program and there is no 0.76 cars, the actual change of red light time will have a error. Assumptions Assumptions are made to the system and required to be considered if implementing in the physical system. They are: • In 1 second, only one car will pass the detector. For instance, when a car is detected, no other car will pass during the 1-second period while the detector generates its digital output. • The number of vehicles on the ramp is significantly smaller than on the freeway, meaning that ramp traffic will not significantly affect freeway capacity.. • None of the output pins require external pull-up resistors. The speed of the output pin response, whether fast or slow edge, is not crucial and either can be used. Program Conceptualization The system is divided into several components, primarily consisting of the LED module, detector module, and timer module. The timer module controls both the detectors and the LEDs. Timer2 manages the flashing of the yellow light, while Timer3 handles the switching between the red and green lights. Timer4 is tasked with adjusting the red light's stop duration. Figure 1: Architecture of the system state The maximum time for the timer is around 3 seconds, which is much shorter than the required 20 seconds. Therefore, the program uses multiple counts to reach 20 seconds. The variable "count" holds the theoretical red light stop time, while "timer count" tracks the current red light stop duration. For instance, if "timer count" is 4 and "count" is 5,it indicates that based on the current traffic flow, the red light should be on for 5 seconds, and it has already been on for approximately 4 seconds (between 4 and 5 seconds). Timer2 controls the yellow light, toggling its state every 0.5 seconds (after one timer interrupt). If the toggle is 1, the yellow light turns on; otherwise, all lights are off, resulting in the yellow light flashing at 1 Hz. Program Implementation To implement the concept into the system, there are few C source files included in the system with their functions: • main.c Main loop of the system • sensor.c Sensor configuration: passing car detect • led.c Led configuration • timer.c Timing and logic control Detailed discussion of each source code is as outlined below. main.c The main.c file is responsible for initializing the LED, sensor, and timer. After checking the flag to determine whether the freeway is currently in peak hours, it activates the appropriate timer and gradually turns on the sensors and LEDs within the timers, based on the timing sequence. Figure 2: Flow chart of main.c source file. The system begins by initializing the LED, timer, and detectors through calls to led_init(), timer2/3/4_init(), and detector_init(), and then starts the peak/off-peak loop. The main function of main.c is to handle switching between peak and off-peak modes, with further operations managed by the timers. At the end of the loop, it activates the detectors and counts the passing vehicles, which will be used by Timer4 to determine whether it is peak or off-peak hours. Timer.c The timer.c file is primarily responsible for handling timing and executing different controls at specified intervals. Timer2 manages the flashing of the yellow light, Timer3 controls the switching between the green and red lights, and Timer4 regulates the duration of the red light and monitors whether the traffic flow is overloaded. Figure 2: Flow chart of timer.c file. In the timer.c file, there are a total of three timers. Timer2 has a period of 0.5 seconds, which means it triggers an interrupt and toggles the value of toggle every 0.5 seconds. When toggle equals 1, the yellow LED will be turned on. As a result, the yellow LED will remain on for 0.5 seconds and then turn off for the next 0.5 seconds, achieving a flashing rate of 1 Hz. The red light will be activated when Timer3 is running. Each time Timer3 triggers an interrupt, timer_count increments by 1 until it reaches count, meaning the red light remains on until Timer3 completes several cycles. Once the red light turns off, timer_count resets to 0, and the green light is activated. Additionally, Timer3 will be turned off, and the ramp detector will be enabled. Timer4 remains active throughout the entire program. It compares the current car_count detected from the freeway with a threshold of 10 to determine whether it is peak time. If it is peak time, the program calculates the overload proportion Sensor.c In this section, three detectors is set to separately monitor car passing on freeway0/1 and ramp. Figure 3: Flow chart of detector function The detector produces a 1-second high pulse. To prevent multiple counts within this 1- second period, two variables, pre_state and cur_state, are defined to determine whether the high signal comes from the same pulse. The count is incremented only when pre_state is 0 and cur_state is 1. After each evaluation, the value of cur_state is assigned to pre_state. Program Operation The digital pins are set as the diagram showed below: Figure 4: output bits P2.1, P2.2, P2.3 are set as output. Figure 4:on/off input bit P2.4, P2.5, P2.6 are set as input. Traffic control: Case 1: off-peak situation In this case, the yellow lamp is flashing at 1Hz, timer2 and timer4 is working. Figure 4: yellow lamp on When toggle is 1, yellow lamp is switched on (P2.2 is 1). From table in watch we can see, the timer4, which counts for 20s, have triggered interrupts for 12 times, and now there have been 6 car passed. Figure 4: yellow lamp off In off-peak situations, the yellow light remains off until the next Timer2 interrupt occurs when toggle is 0. As a result, the yellow light stays on for 0.5 seconds after being off for 0.5 seconds, achieving a flashing rate of 1 Hz. With P2.2 set to 0, the yellow light is turned off. Case 2: Peak situation In this case, red lamp will keep on from 3s to 20s depends on car flow. Figure 4: red lamp on According to the figure, the flag is set to 1, indicating that it is peak time. The red light has been on for approximately 2 seconds. However, since the count is 6, the red light should continue to stay on for about 4 more seconds. With P2.1 set to 1, the red light is turned on. Figure 4: green lamp on From this figure, the count is still 6, but the timer_count1 is 0. This means red lamp have already been switched on for 6s, and then the timer_count will be reset to 0 when the last interrupt was triggered. P2.4 is 1, so the green lamp is switched on. Discussion Although this operation has generally met its objectives, there are several areas that could be improved. First, the vehicles passing through the ramp can affect freeway traffic. While it is assumed that only a few vehicles use the ramp, real-world conditions are variable. Therefore, in the actual ramp meter design, the traffic flow must also account for vehicles passing through the ramp. Second, in this operation, we assume that a maximum of one vehicle can pass in one second, as the detector generates a high-level signal that lasts for one second after detecting a car. Consequently, if two or more vehicles pass within that second, the generated pulse can only register as one vehicle passing. Lastly, the maximum traffic flow of 3,400 vehicles per hour, as mentioned in the task, is not represented in this design. My proposed design to address this requirement involves utilizing a 3-second period for convenience, considering that the maximum timeron a 20MHz CPU is 3.36 seconds. If we take one hour as a cycle, the timer needs to trigger 1,200 interrupts. An array of 1,200 data entries will be created, and each time the timer triggers an interrupt, the pointer will move down to store the detected vehicle at the current position. Once 1,200 interrupts are triggered, the pointer will reset to save the traffic flow and overwrite the first data entry during the 1201st 3-second interval. Conclusion This assignment presents a valuable opportunity to design a ramp meter. The C167 user manual is an essential resource for accurately implementing the timer and configuring I/O ports. Some registers need to be modified before use, and the user manual provides detailed instructions for these modifications. The simulated results further validate the feasibility of the design project. Overall, this project primarily evaluated the use of timers, understanding interrupts, multiple counting methods, and the configuration of basic I/Oports.
ADT202 Assessment Task 2: Interface Concept Proposal INTRODUCTION Each assessment task for this unit builds upon each other to form. a resolved interactive design. In this second assignment, you will leverage user interface (UI) design and user experience (UX) design considerations as you explore and critically analyse potential page layouts for your website, before translating them into low-fidelity wireframes, resolved high-fidelity wireframes (mockups), and interactive prototypes. Students will be introduced to Figma, a powerful tool for designing web and app user interfaces, wireframes, and interactive prototypes to produce designs for a dynamic 4-page website. SUBMISSION DETAILS Timeline: Weeks 4, 5, 6, 7 Due Dates: Compulsory WIP Review: Assessed in class during Week 7 Final Submission: Friday December 20th, 2024 at 8pm Weighting: 30% Deliverables: 1x multi-page PDF document WHAT YOU ARE REQUIRED TO DO For this assignment you are required to develop resolved page designs and working prototypes for a 4-page website catering to both desktop and mobile devices. 1. Page layout exploration Complete the following: Research and document a minimum of 5 websites that make good use of grids as well as websites which break the rules. Explore a minimum of 5 layout sketches per page (4 pages) for your website viewed on desktop (20 sketches total). Explore a minimum of 3 layout sketches per page (4 pages) for your website viewed on mobile (12 total). Demonstrate curiosity and a willingness to take risks as you interrogate the different ways users can interact with your content. Move elements around the page. Play with grid structures, information hierarchy, scale, contrast, balance, and other design principles to see what works effectively and what doesn't. The best work will have a wide variety of exploration at this stage! COMPULSORY IN-CLASS ACTIVITY Follow the Week 4 compulsory in-class activity to explore potential page layout variations via hand-rendered sketches. 2. Low-fidelity wireframes Low-fidelity wireframes are a great tool for understanding and communicating how the pages of a site or screens of an app are composed. Critically analyse your earlier page layout exploration to determine which is the most appropriate, engaging, and effective layout for each page of your site, and translate those into low-fidelity wireframes. We're not looking for content and aesthetics just yet. Simply develop clean and structured layouts for each page. Complete the following: Using Figma, translate your chosen layout sketches into digital low-fidelity wireframes for each of your 4 pages, for both desktop and mobile (8 page designs in total). COMPULSORY IN-CLASS ACTIVITY Follow the Week 4 compulsory in-class activity to create considered and clean low-fidelity wireframes for each page of your website in Figma. 3. High-fidelity wireframes / mockups With the structure and layout of your website finalised, you can now turn to aesthetics and content. High-fidelity wireframes—or mockups—give us a greater sense of how the site will look. They include branded elements such as logos, colour palettes, and typography, as well as appropriate imagery, icons, and buttons. Mockups are a fantastic way to present a concept to clients or teams so that everyone can see what the finished product will look like. Complete the following: Using Figma, build upon your low-fidelity wireframes by adding colour, text, and image content to turn them into high-fidelity wireframes/mockups, for both desktop and mobile (8 page designs in total).. Note: It is a mandatory requirement that ALL imagery used in these websites is created by you. No stock photography or internet images can be used. The use of externally sourced imagery will result in zero marks given for this component. YOU MUST USE THE IMAGES AND TEXT YOU GENERATED FOR ASSIGNMENT 1. COMPULSORY IN-CLASS ACTIVITY Follow the Week 5 compulsory in-class activity to create a resolved, high-fidelity wireframe/mockup of each page of your website in Figma. 4. Interactive Figma prototype While mockups are great, and are a common way to present ideas to clients and teams, interactive prototypes allow designers to take things a big step further and present an early version of a website or app before it's built. This gives everyone an even richer sense of the final outcome and drives more-meaningful insights, as it actually allows the user experience to be tested. Complete the following: Using the Prototype mode in Figma, add interactions to your high-fidelity wireframes/mockups such as linking between pages, hover and click effects, and swipe gestures on mobile. Create one interactive prototype for desktop and one for mobile. Test your desktop prototype on your computer and test your mobile prototype on your phone. COMPULSORY IN-CLASS ACTIVITY Follow the Week 6 compulsory in-class activity to create an interactive prototype of your website in Figma. 5. Participate in the compulsory WIP Review in Week 7 The work-in-progress (WIP) review is an integral part of the project workflow, so it's essential that you participate no matter how much progress you've made. Complete the following: In small groups (on-campus students) or via screensharing (online students), share the progress of your website designs, discussing what you've done so far and where you're going with everything. Provide feedback on other students' work, either in your small groups (on-campus students) or via the online chat (online students). Note: If you are unable to participate in the WIP Review on the day, it is your responsibility to negotiate an alternative presentation of your work with your lecturer prior to the final submission deadline. If the WIP Review is not completed, marks cannot be allocated for it. Follow the Week 7 compulsory in-class activity to participate in the sharing of your work and providing of feedback to others. PREPARE YOUR DOCUMENT FOR SUBMISSION Neatly compile all required components into one multi-page PDF document for submission, including: ✅ Cover page (including your full name, student ID, unit code, and lecturer name) ✅ Page layout exploration (min 5 websites researched, min 20 hand-rendered sketches for desktop and 12 for mobile + annotations) ✅ Low-fidelity wireframes (min 4 digital layouts + annotations for each of desktop and mobile) ✅ High-fidelity wireframes / mockups (min 4 digital designs + annotations for each of desktop and mobile) ✅ Links to your completed interactive Figma prototypes (1x desktop prototype, 1x mobile prototype + development screenshots and annotations) ***TEST YOUR LINKS!*** ✅ WIP Review feedback (including before/after screenshots and annotations of changes made as a result of feedback) ✅ Reference List (ensure your references include name of creator and source/publication where you found it) ✅ Use of AI Statement (refer to Acceptable Use of AI)
Math 425 Fall 2024 - HW 10 Due Sunday 11/10, 11:59pm, via Gradescope Please note: (1). Please include detailed steps. Only providing the result will not get full credits. (2). Please write at most one problem in each page. If you reach the bottom please start a new page instead of writing two columns in one page. If a problem contains multiple small questions, you may write them in one page. (3). Please associate pages with problems in Gradescope. 1. Choose a number X at random from the set of numbers S = {1, 2, 3, 4, 5}. Now choose a number Y at random from the subset {i ∈ S : i ≤ X}. (1). Find the joint mass function fX,Y (i, j). (2). Find the conditional mass function fX|Y (i, j). (3). Are X and Y independent? Why? 2. The joint p.d.f of X and Y is Find the conditional p.d.f fX|Y (x, y). 3. If X and Y has joint p.d.f Compute the joint p.d.f fU,V (u, v), where U = XY and V = X/Y .
MSc in Public Policy SPOLM0074 Researching Public Policy Assignment: Research Proposal Summative assessment: 100% Maximum length of assignment: 3,000 words Submission Date: 12th December (by noon) Formulate a research proposal which aims to address a specific and relevant public policy problem of interest to you. The research project proposed should be deliverable by a sole researcher within six months. Your proposal should be clear, well-justified and achievable within the time-frame. given. More guidance will be provided during the unit delivery. The proposal should contain the following sections: • Presentation of the policy problem and its relevance: using the literature provide a summary of the policy problem and indicate why the study of this problem is important for public policy. • Brief review of the main academic literature and research question (s): present a critical evaluation of the literature related to the problem under study. Identify main themes and gaps in the literature and based on these gaps propose a specific and measurable research question(s). • Research design and methods: Identify and justify the main research design and methods that can help answer your research questions. Highlight any limitations of the methods chosen. • Research ethics: discuss ethical implications of the research proposal presented. • Bibliography To prepare for the summative assessment you will be supported by a formative element consisting of in class group presentations whereby you will be required to critically evaluate a given research proposal. Oral feedback will be provided in class following your presentations. We encourage students to use this summative assessment as a first step towards the MPP dissertation and to initiate discussions with the allocated supervisor. However, changes in topic or methods are admitted after submission. Formal requirements • 3.000 word maximum (excluding figures, tables and bibliography). • Use Harvard referencing style. • Marks and feedback for summative assessment are returned within 15 working days of the submission deadline (excluding public holidays) • For marking criteria, late submission and word count penalty regulations, please refer to the PGT Student Hub