<jupyter_start><jupyter_text>Import the NumPy and Matplotlib modules:<jupyter_code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt<jupyter_output><empty_output><jupyter_text>Exercise 08.1 (function plotting)Consider the function $$f(x) = e^{x/10} \sin(\omega_{1}x)\cos(\omega_{0}x)$$from $x = -4\pi$ to $x = 4\pi$. (1) Plot the function when $\omega_{0} = \omega_{1} = 1$. Label the axes.<jupyter_code>num_points = 100
x = np.linspace(-4*np.pi, 4*np.pi, num=num_points)

f = np.exp(x/10)*np.sin(x)*np.cos(x)
# YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output><jupyter_text>(2) Create an interactive plot with sliders for $\omega_{0}$ and $\omega_{1}$, varying from 0 to 2.<jupyter_code>from ipywidgets import *

# YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output><jupyter_text>Exercise 08.2 (multiple function plotting)Plot the function $$f(x)  = \frac{\sin(x)}{x}$$from $x = -6\pi$ to $x = 6\pi$. Think carefully about which $x$ values you use when $x$ is close to zero.  Add to the above plot the graph of $1/ \left| x \right|$, and limit the range of the $y$ axis to 1 using`plt.ylim`. (Hint: use `np.abs(x)` to return the absolute values of each component of a NumPy array `x`.)<jupyter_code># YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output><jupyter_text>Exercise 08.3 (demographics and interactive plotting)A county planning body has requested an interactive tool to visualise the population distribution in Cambridgeshire (by district) from 2011 to 2021 for different population growth rate scenarios in each district. It can be assumed that:- the growth rates are constant in each district;- the growth rate will not be negative in any district; and - the annual growth rate in any one district will not exceed 10%.Building on the pie chart example with population data in the Activity notebook, create an interactive plot with:1. A slider for the year (from 2011 to 2021); and2. Sliders for the annual population growth for each district (in percentage), with an    initial value of zero for each district.  SolutionThere are number of ways this exercise could be done, from very simple but not very robust with respect to changes in the order of the input data, to quite techical but robust with repsect to the order in which data is entered.<jupyter_code># List of (district, population) data (in 2011)
population_data = (('Cambridge City', 123900), 
                   ('East Cambridgeshire', 83800), 
                   ('Fenland', 95300), 
                   ('Huntingdonshire', 169500), 
                   ('South Cambridgeshire', 148800))

# YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output><jupyter_text>Exercise 08.4 (crime reports by location) BackgroundYour task is to produce a crime report data plot in the neighborhood of your college, by reported crimecategory.We can get crime data in the UK from the police data systems using what is known as a *REST API*,and turn the data into a list of Python dictionaries. Each entry in the list is a police report (an entry is a Python dictionary detailing the report).The first step is to import the modules we will be using:<jupyter_code>import json
import requests<jupyter_output><empty_output><jupyter_text>The service https://data.police.uk has an interface where we can add specific strings to the URL (web address) to define what data we are intersted in, and the police server will return our requested data. The format is    https://data.police.uk/api/crimes-street/all-crime?lat=52.629729&lng=-1.131592&date=2017-01    This return crimes reports within a mile radius of the geographic coordinate point for the month `2017-01`.          Below we create this URL string to include a part of the Cambridge city centre. You can modify this for your own college or other areas of interest (Google Maps is a handy way to get the geographic coordinates).<jupyter_code># A point in the Cambridge city centre
long, lat = 52.205277, 0.119117

# year-month of interest
year_month = '2019-05'

# Construct request URL string
url = "https://data.police.uk/api/crimes-street/all-crime?lat={}&lng={}&date={}".format(long, lat, year_month)

# Fetch data from https://data.police.uk
r = requests.get(url)<jupyter_output><empty_output><jupyter_text>The following converts the fetched data into a list of dictionaries:<jupyter_code>crime_data = r.json()<jupyter_output><empty_output><jupyter_text>To get an idea of how the data is arranged, we can look at the first report in the list. To make the displayed data easier to read, we use the 'pretty print' module `pprint`.<jupyter_code>import pprint
if crime_data:
    pprint.pprint(crime_data[0])<jupyter_output><empty_output><jupyter_text>Each dictionary item corresponds to a reported crime.  TaskProduce a bar chart of the number of reports in different categories. Run your program for different parts of Cambridge, starting with the area around your college, and for different months and years. HintsCreate an empty dictionary, which will eventually map the report category to the number of incidents:<jupyter_code>categories_freq = {}<jupyter_output><empty_output><jupyter_text>Iterate over all reports in the list, and extract the category string from each report. If the category string (the 'key') is already in the dictionary increment the associated counter. Otherwise add the key to the dictionary, and associate the value 1.<jupyter_code># Iterate over all reports
for report in crime_data:
    # Get category type
    category = report['category']
    
    if category in categories_freq:
        # Increment counter here
        pass  # This can be removed once the 'if' block has a body
    else:
        # Add category to dictionary here
        pass  # This can be removed once the 'else' block has a body<jupyter_output><empty_output><jupyter_text>The crime categories are the dictionary keys, which can be extracted using```pythonlist(categories_freq.keys())``` When adding the tick labels (crime categories), it may be necessary to rotate the labels, e.g.:```pythonplt.xticks(x_pos, categories, rotation='vertical')```  Extensions (optional)1. Probe the retrieved data to build a set of all crime categories in the data set.2. Explore the temporal (time) aspect of the data. Thinks of ways to represent the change in reported incident    types over time.3. Explore what other data you can retriev from https://data.police.uk/docs/.  SolutionThere are many ways this exercise could be programmed, and there is some choice in data structures.Build (a) a list of crime categories and (b) the number of reports in each category:<jupyter_code># Empty dictionary
categories_freq = {}

# YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output><jupyter_text>Produce a bar chart:<jupyter_code># Create an array with the position of each bar along the x-axis
x_pos = np.arange(len(categories_freq))

# YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output><jupyter_text>Here is a compact version using dictionary member functions (it will be visible when solutions are released).<jupyter_code># YOUR CODE HERE
raise NotImplementedError()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08100635886093448, 'fraction_numerical': 0.01976776333978435, 'mean_word_length': 4.863047001620745, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 57, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '297716', 'license': 'MIT', 'n_tokens_mistral': 2177, 'n_tokens_neox': 2018, 'n_words': 896, 'path': 'Assignment/08 Exercises.ipynb', 'repo_name': 'reddyprasade/PYTHON-BASIC-FOR-ALL', 'size': '7234'}