markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Calculate the weighted returns for the portfolio assuming an equal number of shares for each stock
# Set weights weights = [1/3, 1/3, 1/3] # Calculate portfolio return # Display sample data
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Join your portfolio returns to the DataFrame that contains all of the portfolio returns
# Join your returns DataFrame to the original returns DataFrame # Only compare dates where return data exists for all the stocks (drop NaNs)
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Re-run the risk analysis with your portfolio to see how it compares to the others Calculate the Annualized Standard Deviation
# Calculate the annualized `std`
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Calculate and plot rolling `std` with 21-day window
# Calculate rolling standard deviation # Plot rolling standard deviation
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Calculate and plot the correlation
# Calculate and plot the correlation
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Calculate and Plot the 60-day Rolling Beta for Your Portfolio compared to the S&P 60 TSX
# Calculate and plot Beta
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Using the daily returns, calculate and visualize the Sharpe ratios using a bar plot
# Calculate Annualized Sharpe Ratios # Visualize the sharpe ratios as a bar plot
_____no_output_____
ADSL
.ipynb_checkpoints/whale.py-checkpoint.ipynb
charbelnehme/pandas-homework
Saying the same thing multiple ways What happens when someone comes across a file in our file format? How do they know what it means? If we can make the tag names in our model globally unique, then the meaning of the file can be made understandablenot just to us, but to people and computers all over the world.Two file formats which give the same information, in different ways, are *syntactically* distinct,but so long as they are **semantically** compatible, I can convert from one to the other. This is the goal of the technologies introduced this lecture. The URI The key concept that underpins these tools is the URI: uniform resource **indicator**. These look like URLs: `www.turing.ac.uk/rsd-engineering/schema/reaction/element`But, if I load that as a web address, there's nothing there!That's fine.A UR**N** indicates a **name** for an entity, and, by using organisational web addresses as a prefix,is likely to be unambiguously unique.A URI might be a URL or a URN, or both. XML Namespaces It's cumbersome to use a full URI every time we want to put a tag in our XML file.XML defines *namespaces* to resolve this:
%%writefile system.xml <?xml version="1.0" encoding="UTF-8"?> <system xmlns="http://www.turing.ac.uk/rsd-engineering/schema/reaction"> <reaction> <reactants> <molecule stoichiometry="2"> <atom symbol="H" number="2"/> </molecule> <molecule stoichiometry="1"> <atom symbol="O" number="2"/> </molecule> </reactants> <products> <molecule stoichiometry="2"> <atom symbol="H" number="2"/> <atom symbol="O" number="1"/> </molecule> </products> </reaction> </system> from lxml import etree with open("system.xml") as xmlfile: tree = etree.parse(xmlfile) print(etree.tostring(tree, pretty_print=True, encoding=str))
<system xmlns="http://www.turing.ac.uk/rsd-engineering/schema/reaction"> <reaction> <reactants> <molecule stoichiometry="2"> <atom symbol="H" number="2"/> </molecule> <molecule stoichiometry="1"> <atom symbol="O" number="2"/> </molecule> </reactants> <products> <molecule stoichiometry="2"> <atom symbol="H" number="2"/> <atom symbol="O" number="1"/> </molecule> </products> </reaction> </system>
CC-BY-3.0
ch09fileformats/11ControlledVocabularies.ipynb
jack89roberts/rsd-engineeringcourse
Note that our previous XPath query no longer finds anything.
tree.xpath("//molecule/atom[@number='1']/@symbol") namespaces = {"r": "http://www.turing.ac.uk/rsd-engineering/schema/reaction"} tree.xpath("//r:molecule/r:atom[@number='1']/@symbol", namespaces=namespaces)
_____no_output_____
CC-BY-3.0
ch09fileformats/11ControlledVocabularies.ipynb
jack89roberts/rsd-engineeringcourse
Note the prefix `r` used to bind the namespace in the query: any string will do - it's just a dummy variable. The above file specified our namespace as a default namespace: this is like doing `from numpy import *` in python. It's often better to bind the namespace to a prefix:
%%writefile system.xml <?xml version="1.0" encoding="UTF-8"?> <r:system xmlns:r="http://www.turing.ac.uk/rsd-engineering/schema/reaction"> <r:reaction> <r:reactants> <r:molecule stoichiometry="2"> <r:atom symbol="H" number="2"/> </r:molecule> <r:molecule stoichiometry="1"> <r:atom symbol="O" number="2"/> </r:molecule> </r:reactants> <r:products> <r:molecule stoichiometry="2"> <r:atom symbol="H" number="2"/> <r:atom symbol="O" number="1"/> </r:molecule> </r:products> </r:reaction> </r:system>
Overwriting system.xml
CC-BY-3.0
ch09fileformats/11ControlledVocabularies.ipynb
jack89roberts/rsd-engineeringcourse
Namespaces and Schema It's a good idea to serve the schema itself from the URI of the namespace treated as a URL, but it's *not a requirement*: it's a URN not necessarily a URL!
%%writefile reactions.xsd <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.turing.ac.uk/rsd-engineering/schema/reaction" xmlns:r="http://www.turing.ac.uk/rsd-engineering/schema/reaction"> <xs:element name="atom"> <xs:complexType> <xs:attribute name="symbol" type="xs:string"/> <xs:attribute name="number" type="xs:integer"/> </xs:complexType> </xs:element> <xs:element name="molecule"> <xs:complexType> <xs:sequence> <xs:element ref="r:atom" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="stoichiometry" type="xs:integer"/> </xs:complexType> </xs:element> <xs:element name="reactants"> <xs:complexType> <xs:sequence> <xs:element ref="r:molecule" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="products"> <xs:complexType> <xs:sequence> <xs:element ref="r:molecule" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="reaction"> <xs:complexType> <xs:sequence> <xs:element ref="r:reactants"/> <xs:element ref="r:products"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="system"> <xs:complexType> <xs:sequence> <xs:element ref="r:reaction" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
Overwriting reactions.xsd
CC-BY-3.0
ch09fileformats/11ControlledVocabularies.ipynb
jack89roberts/rsd-engineeringcourse
Note we're now defining the target namespace for our schema.
with open("reactions.xsd") as xsdfile: schema_xsd = xsdfile.read() schema = etree.XMLSchema(etree.XML(schema_xsd)) parser = etree.XMLParser(schema=schema) with open("system.xml") as xmlfile: tree = etree.parse(xmlfile, parser) print(tree)
<lxml.etree._ElementTree object at 0x106978960>
CC-BY-3.0
ch09fileformats/11ControlledVocabularies.ipynb
jack89roberts/rsd-engineeringcourse
Note the power of binding namespaces when using XML files addressing more than one namespace.Here, we can clearly see which variables are part of the schema defining XML schema itself (bound to `xs`)and the schema for our file format (bound to `r`) Using standard vocabularies The work we've done so far will enable someone who comes across our file format to track down something about its significance, by following the URI in the namespace. But it's still somewhat ambiguous. The word "element" means (at least) two things: an element tag in an XML document, and a chemical element. (It also means a heating element in a toaster, and lots of other things.) To make it easier to not make mistakes as to the meaning of **found data**, it is helpful to usestandardised namespaces that already exist for the concepts our file format refers to.So that when somebody else picks up one of our data files, the meaning of the stuff it describes is obvious. In this example, it would be hard to get it wrong, of course, but in general, defining file formats so that they are meaningful as found data should be desirable. For example, the concepts in our file format are already part of the "DBPedia ontology",among others. So, we could redesign our file format to exploit this, by referencing for example [https://dbpedia.org/ontology/ChemicalCompound](https://dbpedia.org/ontology/ChemicalCompound):
%%writefile chemistry_template3.mko <?xml version="1.0" encoding="UTF-8"?> <system xmlns="https://www.turing.ac.uk/rsd-engineering/schema/reaction" xmlns:dbo="https://dbpedia.org/ontology/"> %for reaction in reactions: <reaction> <reactants> %for molecule in reaction.reactants.molecules: <dbo:ChemicalCompound stoichiometry="${reaction.reactants.molecules[molecule]}"> %for element in molecule.elements: <dbo:ChemicalElement symbol="${element.symbol}" number="${molecule.elements[element]}"/> %endfor </dbo:ChemicalCompound> %endfor </reactants> <products> %for molecule in reaction.products.molecules: <dbo:ChemicalCompound stoichiometry="${reaction.products.molecules[molecule]}"> %for element in molecule.elements: <dbo:ChemicalElement symbol="${element.symbol}" number="${molecule.elements[element]}"/> %endfor </dbo:ChemicalCompound> %endfor </products> </reaction> %endfor </system>
Overwriting chemistry_template3.mko
CC-BY-3.0
ch09fileformats/11ControlledVocabularies.ipynb
jack89roberts/rsd-engineeringcourse
Explorer
modeller = msm.convert('alanine_dipeptide.pdb', to_form='openmm.Modeller') topology = modeller.topology positions = modeller.positions forcefield = app.ForceField('amber10.xml', 'amber10_obc.xml') system = forcefield.createSystem(topology, constraints=app.HBonds, nonbondedMethod=app.NoCutoff) explorer = oe.Explorer(topology, system, platform='CUDA') explorer.set_coordinates(positions) explorer.get_potential_energy() explorer.get_potential_energy_gradient() explorer.get_potential_energy_hessian() coordinates = explorer.get_coordinates() explorer_2 = explorer.replicate() explorer_2
_____no_output_____
MIT
docs/contents/.ipynb_checkpoints/Explorer-checkpoint.ipynb
uibcdf/OpenMembrane
Quenching
explorer.set_coordinates(positions) explorer.quench.l_bfgs() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.quench.fire() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.quench.gradient_descent() explorer.get_potential_energy()
_____no_output_____
MIT
docs/contents/.ipynb_checkpoints/Explorer-checkpoint.ipynb
uibcdf/OpenMembrane
Moves
explorer.set_coordinates(positions) explorer.move.random_atoms_shifts() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_atoms_max_shifts() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_atoms_rsmd() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_atoms_max_rsmd() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_dihedral_shifts() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_dihedral_max_shifts() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_dihedral_rmsd() explorer.get_potential_energy() explorer.set_coordinates(positions) explorer.move.random_dihedral_max_rmsd() explorer.get_potential_energy()
_____no_output_____
MIT
docs/contents/.ipynb_checkpoints/Explorer-checkpoint.ipynb
uibcdf/OpenMembrane
Dynamics
explorer.set_coordinates(positions) explorer.md.langevin(500) explorer.get_potential_energy()
_____no_output_____
MIT
docs/contents/.ipynb_checkpoints/Explorer-checkpoint.ipynb
uibcdf/OpenMembrane
Distance
explorer.set_coordinates(coordinates) explorer.md.langevin(500) explorer.distance.rmsd(positions) explorer.distance.least_rmsd(positions) explorer.set_coordinates(positions) explorer_2 = explorer.replicate() explorer.md.langevin(500) explorer.distance.rmsd(explorer_2) explorer.distance.least_rmsd(explorer_2)
_____no_output_____
MIT
docs/contents/.ipynb_checkpoints/Explorer-checkpoint.ipynb
uibcdf/OpenMembrane
Basic PythonIntroduction to some basic python data types.
x = 1 y = 2.0 s = "hello" l = [1, 2, 3, "a"] d = {"a": 1, "b": 2, "c": 3}
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Operations behave as per what you would expect.
z = x * y print(z) # Getting item at index 3 - note that Python uses zero-based indexing. print(l[3]) # Getting the index of an element print(l.index(2)) # Concatenating lists is just using the '+' operator. print(l + l)
a 1 [1, 2, 3, 'a', 1, 2, 3, 'a']
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Dictionaries are essentially key-value pairs
print(d["c"]) # Getting the value associated with "c"
3
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Numpy and scipy By convention, numpy is import as np and scipy is imported as sp.
import numpy as np import scipy as sp
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
An array is essentially a tensor. It can be an arbitrary number of dimensions. For simplicity, we will stick to basic 1D vectors and 2D matrices for now.
x = np.array([[1, 2, 3], [4, 7, 6], [9, 4, 2]]) y = np.array([1.5, 0.5, 3]) print(x) print(y)
[[1 2 3] [4 7 6] [9 4 2]] [1.5 0.5 3. ]
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
By default, operations are element-wise.
print(x + x) print(x * x) print(y * y) print(np.dot(x, x)) print(np.dot(x, y))
[11.5 27.5 21.5]
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Or you can use the @ operator that is available in Python 3.7 onwards.
print(x @ x) print(x @ y)
[[36 28 21] [86 81 66] [43 54 55]] [11.5 27.5 21.5]
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Numpy also comes with standard linear algebra operations, such as getting the inverse.
print(np.linalg.inv(x))
[[ 0.16949153 -0.13559322 0.15254237] [-0.77966102 0.42372881 -0.10169492] [ 0.79661017 -0.23728814 0.01694915]]
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Eigen values and vectors
print(np.linalg.eig(x))
(array([12.50205135, -3.75787445, 1.2558231 ]), array([[-0.27909662, -0.40149786, 0.3019769 ], [-0.79317124, -0.32770088, -0.78112084], [-0.5412804 , 0.85522605, 0.54649811]]))
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Use of numpy vectorization is key to efficient coding. Here we use the Jupyter %time magic function to demonstrate the relative speeds to two methods of calculation the L2 norm of a very long vector.
r = np.random.rand(10000, 1) %time sum([i**2 for i in r])**0.5 %time np.sqrt(np.sum(r**2)) %time np.linalg.norm(r)
CPU times: user 17.7 ms, sys: 1.14 ms, total: 18.8 ms Wall time: 18.6 ms CPU times: user 86 µs, sys: 30 µs, total: 116 µs Wall time: 93.9 µs CPU times: user 1.33 ms, sys: 347 µs, total: 1.67 ms Wall time: 723 µs
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Scipy has all the linear algebra functions as numpy and more. Moreover, scipy is always compiled with fast BLAS and LAPACK.
import scipy.linalg as linalg linalg.inv(x) import scipy.constants as const print(const.e) print(const.h) import scipy.stats as stats dist = stats.norm(0, 1) # Gaussian distribution dist.cdf(1.96)
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Pandaspandas is one of the most useful packages that you will be using extensively during this course. You should become very familiar with the Series and DataFrame objects in pandas. Here, we will read in a csv (comma-separated value) file downloaded from figshare. While you can certainly manually download the csv and just called pd.read_csv(filename), we will just use the request method to directly grab the file and read it in using a StringIO stream.
import pandas as pd from io import StringIO import requests from IPython.display import display # Get the raw text of the data directly from the figshare url. url = "https://ndownloader.figshare.com/files/13007075" raw = requests.get(url).text # Then reads in the data as a pandas DataFrame. data = pd.read_csv(StringIO(raw)) display(data)
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Here, we will get one column from the DataFrame - this is a Pandas Series object.
print(data["Enorm (eV)"]) df = data[data["Enorm (eV)"] >= 0] df.describe()
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Pandas dataframes come with some conveience functions for quick visualization.
df.plot(x="Enorm (eV)", y="E_raw (eV)", kind="scatter");
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
SeabornHere we demonstrate some basic statistical data visualization using the seaborn package. A helpful resource is the [seaborn gallery](https://seaborn.pydata.org/examples/index.html) which has many useful examples with source code.
import seaborn as sns %matplotlib inline sns.distplot(df["Enorm (eV)"], norm_hist=False); sns.scatterplot(x="Enorm (eV)", y="E_raw (eV)", data=df);
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Materials API using pymatgen The MPRester.query method allows you to perform direct queries to the Materials Project to obtain data. What is returned is a list of dict of properties.
from pymatgen.ext.matproj import MPRester mpr = MPRester() data = mpr.query(criteria="*-O", properties=["pretty_formula", "final_energy", "band_gap", "elasticity.K_VRH"]) # What is returned is a list of dict. Let's just see what the first item in the list looks out. import pprint pprint.pprint(data[0])
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
The above is not very friendly for manipulation and visualization. Thankfully, we can easily convert this to a pandas DataFrame since the DataFrame constructor takes in lists of dicts as well.
df = pd.DataFrame(data) display(df)
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Oftentimes, you only want the subset of data with valid values. In the above data, it is clear that some of the entries do not have elasticity.K_VRH data. So we will use the dropna method of the pandas DataFrame to get a new DataFrame with just valid data. Note that a lot of Pandas methods returns a new DataFrame. This ensures that you always have the original object to compare to. If you want to perform the operation in place, you can usually supply `inplace=True` to the method.
valid_data = df.dropna() print(valid_data)
pretty_formula final_energy band_gap elasticity.K_VRH 1 BaO2 -16.991508 2.1206 28.0 2 BaO -23.550004 2.3711 67.0 5 Bi2O3 -28.415230 1.1772 117.0 6 CeO2 -49.897720 0.6980 148.0 7 CeO2 -51.753294 1.9556 132.0 ... ... ... ... ... 2234 ZnO -105.067224 0.5298 167.0 2251 WO3 -151.123549 0.0000 89.0 2253 WO3 -120.135441 1.8967 37.0 2261 WO3 -120.093040 1.6755 50.0 2267 WO2 -87.834801 0.0000 116.0 [387 rows x 4 columns]
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Seaborn works very well with Pandas DataFrames...
sns.scatterplot(x="band_gap", y="elasticity.K_VRH", data=valid_data);
_____no_output_____
BSD-3-Clause
lectures/notebooks/Lecture 01 - Python for Data Science.ipynb
materialsvirtuallab/nano281
Implement Canny edge detection
# Try Canny using "wide" and "tight" thresholds wide = cv2.Canny(gray, 30, 100) tight = cv2.Canny(gray, 200, 240) # Display the images f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20,10)) ax1.set_title('wide') ax1.imshow(wide, cmap='gray') ax2.set_title('tight') ax2.imshow(tight, cmap='gray')
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/5. Canny Edge Detection.ipynb
Abdulrahman-Adel/CVND-Exercises
TODO: Try to find the edges of this flowerSet a small enough threshold to isolate the boundary of the flower.
# Read in the image image = cv2.imread('images/sunflower.jpg') # Change color to RGB (from BGR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image) # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) ## TODO: Define lower and upper thresholds for hysteresis # right now the threshold is so small and low that it will pick up a lot of noise lower = 70 upper = 210 edges = cv2.Canny(gray, lower, upper) plt.figure(figsize=(20,10)) plt.imshow(edges, cmap='gray')
_____no_output_____
MIT
1_2_Convolutional_Filters_Edge_Detection/5. Canny Edge Detection.ipynb
Abdulrahman-Adel/CVND-Exercises
Load some point-clouds and make two sets (sample_pcs, ref_pcs) from them. The ref_pcs is considered as the __ground-truth__ data while the sample_pcs corresponds to a set that is matched against it, e.g. comes from a generative model.
# top_in_dir = '../data/shape_net_core_uniform_samples_2048/' # Top-dir of where point-clouds are stored. # top_in_dir = '../data/ShapeNetV1PCOutput/' # Top-dir of where point-clouds are stored. top_in_dir = '../data/ShapeNetCore.v2.PC15k/' class_name = 'chair' syn_id = snc_category_to_synth_id()[class_name] class_dir = osp.join(top_in_dir , syn_id, 'val') # all_pc_data = load_all_point_clouds_under_folder(class_dir, n_threads=8, file_ending='.ply', verbose=True) all_pc_data = load_all_point_clouds_under_folder( class_dir, n_threads=8, file_ending='.npy', verbose=True, normalize=True, rotation_axis=1) from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np def plot_3d(pcl, axis=[0,1,2]): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(pcl[:,axis[0]], pcl[:,axis[1]], pcl[:,axis[2]], s=1) ax.set_xlabel('axis-0') ax.set_ylabel('axis-1') ax.set_zlabel('axis-2') plt.show() from random import choice pcls, _, _ = all_pc_data.next_batch(100) plot_3d(pcls[choice(range(pcls.shape[0]))], axis=[0,2,1]) top_in_dir = '../data/ModelNet40.PC15k/' # class_name = raw_input('Give me the class name (e.g. "chair"): ').lower() class_name = "chair" class_dir = osp.join(top_in_dir , class_name, 'test') # all_pc_data = load_all_point_clouds_under_folder(class_dir, n_threads=8, file_ending='.ply', verbose=True) all_pc_data = load_all_point_clouds_under_folder( class_dir, n_threads=8, file_ending='.npy', verbose=True, normalize=True, rotation_axis=1) from random import choice pcls, _, _ = all_pc_data.next_batch(100) plot_3d(pcls[choice(range(pcls.shape[0]))], axis=[0,2,1])
_____no_output_____
MIT
notebooks/VisualizeRotation.ipynb
stevenygd/latent_3d_points
Python programming for [email protected] Agenda1. Background, why Python, [installation](installation), IDE, setup2. Variables, Boolean, None, numbers (integers, floating point), check type3. List, Set, Dictionary, Tuple4. Text and regular expressions5. Conditions, loops6. Objects and Functions7. Special functions (range, enumerate, zip), Iterators8. I/O working with files, working directory, projects9. Packages, pip, selected packages (xmltodict, biopython, xlwings, pyautogui, sqlalchemy, cx_Oracle, pandas)10. Errors and debugging (try, except)11. virtual environments What is a Programming language?![images/image1.png](images/image1.png) Why Python Advantages:* Opensource/ free - explanation* Easy to learn* Old* Popular* All purpose* Simple syntaxis* High level* Scripting* Dynamically typed Disadvantages:* Old* Dynamically typed* Inconsistent development Installation[Python](http://python.org/)[Anaconda](https://www.anaconda.com/products/individual) Integrated Development Environment (IDE)* IDLE – comes with Python* [Jupiter notebook](https://jupyter.org/install)* [google colab](https://colab.research.google.com/notebooks/basic_features_overview.ipynbscrollTo=KR921S_OQSHG)* Spyder – comes with Anaconda* [Visual Studio Code](https://code.visualstudio.com/)* [PyCharm community](https://www.jetbrains.com/toolbox-app/) Python filesPython files are text files with .py extension CommentsComments are pieces of code that are not going to be executed. In python everything after hashtag () on the same line is comment.Comments are used to describe code: what is this particular piece of code doing and why you have created it.
# this is a comment it will be ignored when running the python file
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
VariablesAssigning value to a variable
my_variable = 3 print(my_variable)
3
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Naming variablesVariable names cannot start with the number, cannot contain special characters or space except _Should not be name of python function.* variable1 -> this is OK* 1variable -> this is not OK* Important-variable! -> this is not OK* myVariable -> this is OK* my_variable -> this is OK Data types Numbers 1. integers (whole numbers)
var2 = 2 my_variable + var2 print(my_variable + 4) my_variable = 6 print(my_variable +4)
7 10
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
we can assign the result to another variable
result = my_variable + var2 print(result)
8
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
2. Doubles (floating point number)
double = 2.05 print(double)
2.05
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Mathematical operations- Additon and substraction
2 + 3 5 - 2
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
- Multiplication and division
2 * 3 6 / 2
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Note: the result of division is float not int! - Exponential
2 ** 4 # 2**4 is equal to 2*2*2*2
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
- Floor division
7 // 3
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
7/3 is 2.3333 the floor division is giving the whole number 2 (how many times you can fit 3 in 7) - Modulo
7.0 % 2
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
7//3 is 2, modulo is giving the remainder of the operation (what is left when you fit 2 times 3 in 7 ; 7 =2*3 + 1)Note: Floor division and modulo results are inegers if integers are used as arguments and float if one of the arguments is float Special variables 1. NoneNone means variable without data type, nothing
var = None print(var)
None
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
2. BoleanNote: Bolean is type of integer that can take only values of 0 or 1
var = True # or 1 var2 = False # or 0 print(var) print(var+1)
True 2
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Check variable type 1. type() function
print(type(True)) print(type(1)) print(type(my_variable))
<class 'bool'> <class 'int'> <class 'int'>
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
2. isinstance() function
print(isinstance(True, bool)) print(isinstance(False, int)) print(isinstance(1, int))
True True True
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Comparing variables
print(1 == 1) print(1 == 2) print(1 != 2) print(1 < 2) print(1 > 2) my_variable = None print(my_variable == None) print(my_variable is None) my_variable = 1.5 print(my_variable == 1.5) print(my_variable is 1.5) print(my_variable is not None)
True True True False True
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Note as a general rule of thumb use "is" "is not" when checking if variable is **None**, **True** or **False** in all other cases use "==" Converting Int to Float and vs versa 1. float() function
float(3)
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
2. int() functionNote the int() conversion is taking in to account only the whole number int(2.9) = 2!
int(2.9)
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Tupletuple is a collection which is ordered and unchangeable.
my_tuple = (3, 8, 5, 7, 5)
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
access tuple items by index Note Python is 0 indensing language = it starts to count from 0! ![images/image3.png](images/image3.png)
print(my_tuple[0]) print(my_tuple[2:4]) print(my_tuple[2:]) print(my_tuple[:2]) print(my_tuple[-1]) print(my_tuple[::3]) print(my_tuple[1::2]) print(my_tuple[::-1]) print(my_tuple[-2::])
3 (5, 7) (5, 7, 5) (3, 8) 5 (3, 7) (8, 7) (5, 7, 5, 8, 3) (7, 5)
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Tuple methodsMethods are functions inside an object (every variable in Python is an object) 1.count() method - Counts number of occurrences of item in a tuple
my_tuple.count(6)
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
2.index() method - Returns the index of first occurence of an item in a tuple
my_tuple.index(5)
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Other operations with tuplesAdding tuples
my_tuple + (7, 2, 1)
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Nested tuples = tuples containing tuples
tuple_of_tuples = ((1,2,3),(3,4,5)) print(tuple_of_tuples) print(tuple_of_tuples[0]) print(tuple_of_tuples[1][2])
((1, 2, 3), (3, 4, 5)) (1, 2, 3) 5
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
ListList is a collection which is ordered and changeable.
my_list = [3, 8, 5, 7, 5]
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Accesing list members is exactly the same as accesing tuple members, .count() and .index() methods work the same way with lists.The difference is that list members can be changed
my_list[1] = 9 print(my_list) my_tuple[1] = 9
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Lists are having more methods than tuples 1.count() method same as with tuple 2.index() methodsame as with tuple 3.reverse() methodinverting the list same as my_list[::-1]
my_list.reverse() print(my_list) my_list = my_list[::-1] print(my_list)
[5, 7, 5, 9, 3] [3, 9, 5, 7, 5]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
4.sort() methodsorting the list from smallest to largest or alphabetically in case of text
my_list.sort() print(my_list) my_list.sort(reverse=True) print(my_list)
[3, 5, 5, 7, 9] [9, 7, 5, 5, 3]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
5.clear() methodremoving everything from a list, equal to my_list = []
my_list.clear() print(my_list)
[]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
6.remove() methodRemoves the first item with the specified value
my_list = [3, 8, 5, 7, 5] my_list.remove(7) print(my_list)
[3, 8, 5, 5]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
7.pop() methodRemoves the element at the specified position
my_list.pop(0) print(my_list)
[8, 5, 5]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
8.copy() methodReturns a copy of the list
my_list_copy = my_list.copy() print(my_list_copy)
[3, 8, 5, 7, 5]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
what is the problem with my_other_list = my_list?
my_other_list = my_list print(my_other_list) my_list.pop(0) print(my_list) print(my_list_copy) print(my_other_list) my_other_list.pop(0) print(my_list) print(my_list_copy) print(my_other_list)
[5, 7, 5] [3, 8, 5, 7, 5] [5, 7, 5]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
9.insert() methodAdds an element at the specified position, displacing the following members with 1 position
my_list = [3, 8, 5, 7, 5] my_list.insert(3, 1) print(my_list)
[3, 8, 5, 1, 7, 5]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
10.append() methodAdds an element at the end of the list
my_list.append(6) print(my_list) my_list.append([6,7]) print(my_list)
[3, 8, 5, 1, 7, 5, 6] [3, 8, 5, 1, 7, 5, 6, [6, 7]]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
11.extend() methoddd the elements of a list (or any iterable), to the end of the current list
another_list = [2, 6, 8] my_list.extend(another_list) print(my_list) another_tuple = (2, 6, 8) my_list.extend(another_tuple) print(my_list)
[3, 8, 5, 1, 7, 5, 6, 2, 6, 8, 2, 6, 8]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
End of first session SetSet is an unordered collection of unique objects.
my_set = {3, 8, 5, 7, 5} print(my_set) print(my_set)
{8, 3, 5, 7}
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Set methods.add() - Adds an element to the set.clear() - Removes all the elements from the set.copy() - Returns a copy of the set.difference() - Returns a set containing the difference between two or more sets.difference_update() - Removes the items in this set that are also included in another, specified set.discard() - Remove the specified item.intersection() - Returns a set, that is the intersection of two other sets.intersection_update() - Removes the items in this set that are not present in other, specified set(s).isdisjoint() - Returns whether two sets have a intersection or not.issubset() - Returns whether another set contains this set or not.issuperset() - Returns whether this set contains another set or not.pop() - Removes an element from the set.remove() - Removes the specified element.symmetric_difference() - Returns a set with the symmetric differences of two sets.symmetric_difference_update() - Inserts the symmetric differences from this set and another.union() - Return a set containing the union of sets.update() - Update the set with the union of this set and others
set_a = {1,2,3,4,5} set_b = {4,5,6,7,8} print(set_a.union(set_b)) print(set_a.intersection(set_b))
{1, 2, 3, 4, 5, 6, 7, 8} {4, 5}
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Converting tuple to list to set we can convert any tuple or set to list with **list()** functionwe can convert any list or set to tuple with **tuple()** functionwe can convert any tuple or list to set with **set()** function
my_list = [3, 8, 5, 7, 5] print(my_list) my_tuple = tuple(my_list) print(my_tuple) my_set =set(my_list) print(my_set) my_list2 = list(my_set) print(my_list2)
[3, 8, 5, 7, 5] (3, 8, 5, 7, 5) {8, 3, 5, 7} [8, 3, 5, 7]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
this functions can be nested
my_unique_list = list(set(my_list)) print(my_unique_list)
[8, 3, 5, 7]
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Checking if something is in a list, set, tuple
print(3 in my_set) print(9 in my_set) print(3 in my_list) print(9 in my_tuple)
True False True False
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Dictionarydictionary is a collection which is unordered, changeable and indexed as a key-value pair
my_dict = {1: 2.3, 2: 8.6} print(my_dict[2]) print(my_dict[3]) print(my_dict.keys()) print(my_dict.values()) print(1 in my_dict.keys()) print(2.3 in my_dict.values()) print(my_dict.items())
dict_keys([1, 2]) dict_values([2.3, 8.6]) True True dict_items([(1, 2.3), (2, 8.6)])
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Stringsstrings are ordered sequence of characters, strings are unchangable
print(my_dict.get(2)) my_string = 'this is string' other_string = "this is string as well" multilane_string = '''this is a multi lane string''' print(my_string) print(other_string) print(multilane_string) my_string = 'this "word" is in quotes' my_other_string = "This is Maria's book" print(my_string) print(my_other_string) my_string = "this \"word\" is in quotes" my_other_string = 'This is Maria\'s book' print(my_string) print(my_other_string) my_number = 9 my_string = '9' print(my_number+1) print(my_string+1) print(my_string+'1') print(int(my_string)+1) print(my_number+int('1'))
91 10 10
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Accesing list members is exactly the same as with lists and tuples
print(other_string) print(other_string[0]) print(other_string[::-1])
this is string as well t llew sa gnirts si siht
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
String methods.capitalize() - Converts the first character to upper case.casefold() - Converts string into lower case.center() - Returns a centered string.count() - Returns the number of times a specified value occurs in a string.encode() - Returns an encoded version of the string.endswith() - Returns true if the string ends with the specified value.expandtabs() - Sets the tab size of the string.find() - Searches the string for a specified value and returns the position of where it was found.format() - Formats specified values in a string.format_map() - Formats specified values in a string.index() - Searches the string for a specified value and returns the position of where it was found.isalnum() - Returns True if all characters in the string are alphanumeric.isalpha() - Returns True if all characters in the string are in the alphabet.isdecimal() - Returns True if all characters in the string are decimals.isdigit() - Returns True if all characters in the string are digits.isidentifier() - Returns True if the string is an identifier.islower() - Returns True if all characters in the string are lower case.isnumeric() - Returns True if all characters in the string are numeric.isprintable() - Returns True if all characters in the string are printable.isspace() - Returns True if all characters in the string are whitespaces.istitle() - Returns True if the string follows the rules of a title.isupper() - Returns True if all characters in the string are upper case.join() - Joins the elements of an iterable to the end of the string.ljust() - Returns a left justified version of the string.lower() - Converts a string into lower case.lstrip() - Returns a left trim version of the string.maketrans() - Returns a translation table to be used in translations.partition() - Returns a tuple where the string is parted into three parts.replace() - Returns a string where a specified value is replaced with a specified value.rfind() - Searches the string for a specified value and returns the last position of where it was found.rindex() - Searches the string for a specified value and returns the last position of where it was found.rjust() - Returns a right justified version of the string.rpartition() - Returns a tuple where the string is parted into three parts.rsplit() - Splits the string at the specified separator, and returns a list.rstrip() - Returns a right trim version of the string.split() - Splits the string at the specified separator, and returns a list.splitlines() - Splits the string at line breaks and returns a list.startswith() - Returns true if the string starts with the specified value.strip() - Returns a trimmed version of the string.swapcase() - Swaps cases, lower case becomes upper case and vice versa.title() - Converts the first character of each word to upper case.translate() - Returns a translated string.upper() - Converts a string into upper case.zfill() - Fills the string with a specified number of 0 values at the beginning
my_string = ' string with spaces ' print(my_string) my_stripped_string = my_string.strip() print(my_stripped_string) print('ABC' == 'ABC') print('ABC' == ' ABC ') list_of_words = my_string.split() print(list_of_words) text = 'id1, id2, id3, id4' ids_list = text.split(', ') print(ids_list) new_text = ' / '.join(ids_list) print(new_text) xml_text = 'this is <body>text</body> with xml tags' xml_text.find('<body>') xml_body = xml_text[xml_text.find('<body>')+len('<body>'):xml_text.find('</body>')] print(xml_body)
text
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Other operations with stringscombinig (adding) strings
text = 'text1'+'text2' print(text) text = 'text1'*4 print(text)
text1text1text1text1
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
row and formated string
file_location = 'C:\Users\U6047694\Documents\job\Python_Projects\file.txt' file_location = r'C:\Users\U6047694\Documents\job\Python_Projects\file.txt' print(file_location) var1 = 5 var2 = 6 print(f'Var1 is: {var1}, var2 is: {var2} and the sum is: {var1+var2}') # this is the same as print('Var1 is: '+str(var1)+', var2 is: '+str(var2)+' and the sum is: '+str(var1+var2))
Var1 is: 5, var2 is: 6 and the sum is: 11 Var1 is: 5, var2 is: 6 and the sum is: 11
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Regular expressions in PythonThe regular expressions in python are stored in separate package **re** this package should be imported in order to access its functionality (methods). Methods in re package* re.search() - Check if given pattern is present anywhere in input string. Output is a re.Match object, usable in conditional expressions* re.fullmatch() - ensures pattern matches the entire input string* re.compile() - Compile a pattern for reuse, outputs re.Pattern object* re.sub() - search and replace* re.escape() - automatically escape all metacharacters* re.split() - split a string based on RE text matched by the groups will be part of the output* re.findall() - returns all the matches as a list* re.finditer() - iterator with re.Match object for each match* re.subn() - gives tuple of modified string and number of substitutions re characters'.' - Match any character except newline'^' - Match the start of the string'$' - Match the end of the string'*' - Match 0 or more repetitions'+' - Match 1 or more repetitions'?' - Match 0 or 1 repetitions re set of characters'[]' - Match a set of characters'[a-z]' - Match any lowercase ASCII letter'[lower-upper]' - Match a set of characters from lower to upper'[^]' - Match characters NOT in a setCheet Sheetre reference
text = 'this is a sample text for re testing' t_words = re.findall('t[a-z]* ', text) print(t_words) new_text = re.sub('t[a-z]* ', 'replace ', text) print(new_text)
['this ', 'text '] replace is a sample replace for re testing
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Conditions IF, ELIF, ELSE conditionsif condition sintacsis:
a = 3 if a == 2: print('a is 2') if a == 3: print('a is 3') else: print('a is not 2') if a == 2: pring('a is 2') elif a == 3: print('a is 3') else: print('a is not 2 or 3') if a == 2: pring('a is 2') if a == 3: print('a is 3') else: print('a is not 2 or 3') if a > 2: print('a is bigger than 2') if a < 4: print('a is smaller than 4') else: print('a is something else') if a > 2: print('a is bigger than 2') elif a < 4: print('a is smaller than 4') else: print('a is something else')
a is bigger than 2
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
OR / AND in conditional statement
b = 4 if a > 2 or b < 2: print(f'a is: {a} b is: {b}.')
a is: 3 b is: 4.
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Nested conditional statements
a = 2 if a == 2: if b > a: print('b is bigger than a') else: print('b is not bigger than a') else: print(f'a is {a}')
b is bigger than a
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Loops FOR loop
my_list = [1, 3, 5] for item in my_list: print(item)
1 3 5
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
WHILE loop
a = 0 while a < 5: a = a + 1 # or alternatively a += 1 print(a)
1 2 3 4 5
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
You can put else statement in the while loop as well
a = 3 while a < 5: a = a + 1 # or alternatively a += 1 print(a) else: print('This is the end!')
4 5 This is the end!
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Loops can be nested as well
columns = ['A', 'B', 'C'] rows = [1, 2, 3] for column in columns: print(column) for row in rows: print(row)
A 1 2 3 B 1 2 3 C 1 2 3
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
Break and Continue. Break is stopping the loop, continue is skipping to the next item in the loop
for column in columns: print(column) if column == 'B': break
A B
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
If we have nested loops break will stop only the loop in which is used
columns = ['A', 'B', 'C'] rows = [1, 2, 3] for column in columns: print(column) for row in rows: print(row) if row == 2: break i = 0 while i < 6: i += 1 if i == 3: continue print(i)
1 2 4 5 6
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
ObjectsEverything in Python is Object![images/image4.png](images/image4.png)
class Player: def __init__(self, name): self.name = name print(f'{self.name} is a Player') def run(self): return f'{self.name} is running' player1 = Player('Messi') player1.run()
Messi is a Player
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
InheritanceInheritance allows us to define a class that inherits all the methods and properties from another class.Parent class is the class being inherited from, also called base class.Child class is the class that inherits from another class, also called derived class.
class Futbol_player(Player): def kick_ball(self): return f'{self.name} is kicking the ball' class Basketball_player(Player): def catch_ball(self): return f'{self.name} is catching the ball' player2 = Futbol_player('Leo Messi') player2.kick_ball() player2.run() player3 = Basketball_player('Pau Gasol') player3.catch_ball() player3.kick_ball() class a_list(list): def get_3_element(self): return self[3] my_list = ['a', 'b', 'c', 'd'] my_a_list = a_list(['a', 'b', 'c', 'd']) my_a_list.get_3_element() my_list.get_3_element() my_a_list.count('a')
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
FunctionsA function is a block of code which only runs when it is called.You can pass data, known as arguments or parameters, into a function.A function can return data as a result or not.
def my_func(n): '''this is power function''' result = n*n return result
_____no_output_____
MIT
Python for beginners.ipynb
avkch/Python-for-beginners
You can assign the result of a function to another variable
power5 = my_func(5) print(power5)
25
MIT
Python for beginners.ipynb
avkch/Python-for-beginners