repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
vzg100/Post-Translational-Modification-Prediction
.ipynb_checkpoints/Lysine Acetylation -MLP-checkpoint.ipynb
mit
from pred import Predictor from pred import sequence_vector from pred import chemical_vector """ Explanation: Template for test End of explanation """ par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Training/k_acetylation.csv") y.process_data(vector_function="sequence", amino_acid="K", imbalance_function=i, random_data=0) y.supervised_training("mlp_adam") y.benchmark("Data/Benchmarks/acet.csv", "K") del y print("x", i) x = Predictor() x.load_data(file="Data/Training/k_acetylation.csv") x.process_data(vector_function="sequence", amino_acid="K", imbalance_function=i, random_data=1) x.supervised_training("mlp_adam") x.benchmark("Data/Benchmarks/acet.csv", "K") del x """ Explanation: Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using K acytelation. Training data is from CUCKOO group and benchmarks are from dbptm. End of explanation """ par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"] for i in par: print("y", i) y = Predictor() y.load_data(file="Data/Training/k_acetylation.csv") y.process_data(vector_function="chemical", amino_acid="K", imbalance_function=i, random_data=0) y.supervised_training("mlp_adam") y.benchmark("Data/Benchmarks/acet.csv", "K") del y print("x", i) x = Predictor() x.load_data(file="Data/Training/k_acetylation.csv") x.process_data(vector_function="chemical", amino_acid="K", imbalance_function=i, random_data=1) x.supervised_training("mlp_adam") x.benchmark("Data/Benchmarks/acet.csv", "K") del x """ Explanation: Chemical Vector End of explanation """
gaufung/Data_Analytics_Learning_Note
python-statatics-tutorial/advance-theme/Python-Advance.ipynb
mit
num=[1,2,3] iter(num) num.__iter__() num.__reversed__() it = iter(num) print it.next() print it.next() print it.next() print it.next() """ Explanation: Python 进阶 1 迭代器、生成表达式和生成器 1.1 迭代器(iterators) 迭代器对象拥有个next方法用来表达下一个对象,并且如果导到了最后一个,将会抛出一个StopIteration的异常 End of explanation """ (i for i in num) [i for i in num] """ Explanation: 通过for语句可以来进行迭代整个迭代器的对象。 1.2 生成表达式(generate expression) 生成迭代器的另外一种方法是通过生成表达式 End of explanation """ {i for i in range(3)} {i:i**2 for i in range(3)} """ Explanation: 不仅仅可以生成列表,还有生成集合(set)或者是字典,只要在外边添加一组{}即可 End of explanation """ def f(): yield 1 yield 2 f() gen=f() gen.next() gen.next() gen.next() """ Explanation: 1.3 生成器(generator) 生成器函数通过yield关键字来处理迭代器的生成,每当next函数被调用,将会执行一次yield操作,直至yield操作全部完成。 End of explanation """ def f(): print '---first---' yield 3 print '---middle---' yield 4 print '---finish---' gen=f() gen.next() gen.next() gen.next() """ Explanation: 再看一个生成器的实例,观察该函数如何被调用的 End of explanation """ def simple_decorator(f): print 'decorator' return f @simple_decorator def f(): print 'origin function' f() """ Explanation: 在gen=f()处,函数并没有被调用,而是在第一次调用next()函数的时候,执行print '---first---'语句,当执行最后的next()语句的时候执行了最后的print '---finish---'语句。 2 装饰器 由于在Python中函数也是一种对象,所以可以将其进行传递,通过装饰器可以修改一个函数的行为。 End of explanation """ def para_decorator(f): def _wrapper(*args,**kw): print 'para decorator' return f(*args,**kw) return _wrapper @para_decorator def f(name): print 'name is {}.'.format(name) f('gaufung') """ Explanation: 需要装饰的函数会有一些参数,可以使用通用的参数形式*args,**kw来适应所有情况 End of explanation """ def paras_decorator(value): def para_decorator(f): def _wrapper(*args,**kw): print value return f(*args,**kw) return _wrapper return para_decorator @paras_decorator('zhangsan') def f(name): print 'name is {}.'.format(name) f('gaufung') """ Explanation: 有时装饰器函数也接受参数,则装饰器函数需要进一步封装。 End of explanation """ import functools def decorator_f(f): @functools.wraps(f) def _wrapper(*args,**kw): return f(*args,**kw) return _wrapper @decorator_f def f(): pass """ Explanation: 通常通过装饰器处理的函数,会改变整个函数的签名,为了不改变被装饰函数的签名,需要进一步处理。 End of explanation """ class A(object): def __init__(self,args): self._args = args @classmethod def say(cls): print 'say hello' A.say() """ Explanation: 2.1 标准库中的装饰器 classmethod 方法中如果标记为 @classmethod 那么该函数将被类调用,而不是被类的实例对象调用。该方法参数中不用self,而是cls End of explanation """ class B(object): def __init__(self,arg): self._args = arg @staticmethod def speak(): print 'speak hello' B.speak() """ Explanation: staticmethod 可以通过类所在的命名空间方位该函数,通常来讲用来该函数的前缀为_,用来表明该函数与这个类相关,虽然这个函数不是必须的。 End of explanation """ class deprecated(object): def __call__(self,func): self.func = func self.count = 0 return self._wrapper def _wrapper(self,*args,**kw): self.count += 1 if self.count == 1: print self.func.__name__,'is deprecated.' return self.func(*args,**kw) @deprecated() def f(): pass f() """ Explanation: property 通过property的装饰器,可以使用简介的set和get操作,方便使用。 2.2 添加deprecate信息 如果一个函数如果已经被丢弃,当用户在第一次使用该函数的时候,输出相关信息。 类实现 End of explanation """ def deprecated(func): count = [0] def _wrapper(*args,**kw): count[0] += 1 if count[0] == 1: print func.__name__,'is deprecated' return func(*args,**kw) return _wrapper @deprecated def f(): pass f() """ Explanation: 函数实现 End of explanation """
kingsgeocomp/applied_gsa
Practical-06-2. Exploration.ipynb
mit
from sklearn.decomposition import PCA """ Explanation: Dimensionality Reduction End of explanation """ o_dir = os.path.join('outputs','pca') if os.path.isdir(o_dir) is not True: print("Creating '{0}' directory.".format(o_dir)) os.mkdir(o_dir) pca = PCA() # Use all Principal Components pca.fit(scdf) # Train model on all data pcdf = pd.DataFrame(pca.transform(scdf)) # Transform data using model for i in range(0,21): print("Amount of explained variance for component {0} is: {1:6.2f}%".format(i, pca.explained_variance_ratio_[i]*100)) print("The amount of explained variance of the SES score using each component is...") sns.lineplot(x=list(range(1,len(pca.explained_variance_ratio_)+1)), y=pca.explained_variance_ratio_) pca = PCA(n_components=11) pca.fit(scdf) scores = pd.DataFrame(pca.transform(scdf), index=scdf.index) scores.to_csv(os.path.join(o_dir,'Scores.csv.gz'), compression='gzip', index=True) # Adapted from https://stackoverflow.com/questions/22984335/recovering-features-names-of-explained-variance-ratio-in-pca-with-sklearn i = np.identity(scdf.shape[1]) # identity matrix coef = pca.transform(i) loadings = pd.DataFrame(coef, index=scdf.columns) loadings.to_csv(os.path.join(o_dir,'Loadings.csv.gz'), compression='gzip', index=True) print(scores.shape) scores.sample(5, random_state=42) print(loadings.shape) loadings.sample(5, random_state=42) odf = pd.DataFrame(columns=['Variable','Component Loading','Score']) for i in range(0,len(loadings.index)): row = loadings.iloc[i,:] for c in list(loadings.columns.values): d = {'Variable':loadings.index[i], 'Component Loading':c, 'Score':row[c]} odf = odf.append(d, ignore_index=True) g = sns.FacetGrid(odf, col="Variable", col_wrap=4, height=3, aspect=2.0, margin_titles=True, sharey=True) g = g.map(plt.plot, "Component Loading", "Score", marker=".") """ Explanation: Principal Components Analysis End of explanation """ sns.set_style('white') sns.jointplot(data=scores, x=0, y=1, kind='hex', height=8, ratio=8) """ Explanation: What Have We Done? End of explanation """ o_dir = os.path.join('outputs','clusters-pca') if os.path.isdir(o_dir) is not True: print("Creating '{0}' directory.".format(o_dir)) os.mkdir(o_dir) score_df = pd.read_csv(os.path.join('outputs','pca','Scores.csv.gz')) score_df.rename(columns={'Unnamed: 0':'lsoacd'}, inplace=True) score_df.set_index('lsoacd', inplace=True) # Ensures that df is initialised but original scores remain accessible df = score_df.copy(deep=True) score_df.describe() score_df.sample(3, random_state=42) """ Explanation: Create an Output Directory and Load the Data End of explanation """ scaler = preprocessing.MinMaxScaler() df[df.columns] = scaler.fit_transform(df[df.columns]) df.describe() df.sample(3, random_state=42) """ Explanation: Rescale the Loaded Data We need this so that differences in the component scores don't cause the clustering algorithms to focus only on the 1st component. End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/inm/cmip6/models/sandbox-3/landice.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inm', 'sandbox-3', 'landice') """ Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: INM Source ID: SANDBOX-3 Topic: Landice Sub-Topics: Glaciers, Ice. Properties: 30 (21 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:05 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --> Software Properties 3. Grid 4. Glaciers 5. Ice 6. Ice --> Mass Balance 7. Ice --> Mass Balance --> Basal 8. Ice --> Mass Balance --> Frontal 9. Ice --> Dynamics 1. Key Properties Land ice key properties 1.1. Overview Is Required: TRUE    Type: STRING    Cardinality: 1.1 Overview of land surface model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE    Type: STRING    Cardinality: 1.1 Name of land surface model code End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.ice_albedo') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "prescribed" # "function of ice age" # "function of ice density" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Ice Albedo Is Required: TRUE    Type: ENUM    Cardinality: 1.N Specify how ice albedo is modelled End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.atmospheric_coupling_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.4. Atmospheric Coupling Variables Is Required: TRUE    Type: STRING    Cardinality: 1.1 Which variables are passed between the atmosphere and ice (e.g. orography, ice mass) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.oceanic_coupling_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.5. Oceanic Coupling Variables Is Required: TRUE    Type: STRING    Cardinality: 1.1 Which variables are passed between the ocean and ice End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "ice velocity" # "ice thickness" # "ice temperature" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.6. Prognostic Variables Is Required: TRUE    Type: ENUM    Cardinality: 1.N Which variables are prognostically calculated in the ice model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --> Software Properties Software properties of land ice code 2.1. Repository Is Required: FALSE    Type: STRING    Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Code Version Is Required: FALSE    Type: STRING    Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Code Languages Is Required: FALSE    Type: STRING    Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3. Grid Land ice grid 3.1. Overview Is Required: TRUE    Type: STRING    Cardinality: 1.1 Overview of the grid in the land ice scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3.2. Adaptive Grid Is Required: TRUE    Type: BOOLEAN    Cardinality: 1.1 Is an adative grid being used? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.base_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.3. Base Resolution Is Required: TRUE    Type: FLOAT    Cardinality: 1.1 The base resolution (in metres), before any adaption End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.resolution_limit') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.4. Resolution Limit Is Required: FALSE    Type: FLOAT    Cardinality: 0.1 If an adaptive grid is being used, what is the limit of the resolution (in metres) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.projection') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.5. Projection Is Required: TRUE    Type: STRING    Cardinality: 1.1 The projection of the land ice grid (e.g. albers_equal_area) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4. Glaciers Land ice glaciers 4.1. Overview Is Required: TRUE    Type: STRING    Cardinality: 1.1 Overview of glaciers in the land ice scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 4.2. Description Is Required: TRUE    Type: STRING    Cardinality: 1.1 Describe the treatment of glaciers, if any End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.dynamic_areal_extent') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 4.3. Dynamic Areal Extent Is Required: FALSE    Type: BOOLEAN    Cardinality: 0.1 Does the model include a dynamic glacial extent? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Ice Ice sheet and ice shelf 5.1. Overview Is Required: TRUE    Type: STRING    Cardinality: 1.1 Overview of the ice sheet and ice shelf in the land ice scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.grounding_line_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "grounding line prescribed" # "flux prescribed (Schoof)" # "fixed grid size" # "moving grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 5.2. Grounding Line Method Is Required: TRUE    Type: ENUM    Cardinality: 1.1 Specify the technique used for modelling the grounding line in the ice sheet-ice shelf coupling End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.ice_sheet') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.3. Ice Sheet Is Required: TRUE    Type: BOOLEAN    Cardinality: 1.1 Are ice sheets simulated? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.ice_shelf') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 5.4. Ice Shelf Is Required: TRUE    Type: BOOLEAN    Cardinality: 1.1 Are ice shelves simulated? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.surface_mass_balance') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Ice --> Mass Balance Description of the surface mass balance treatment 6.1. Surface Mass Balance Is Required: TRUE    Type: STRING    Cardinality: 1.1 Describe how and where the surface mass balance (SMB) is calulated. Include the temporal coupling frequeny from the atmosphere, whether or not a seperate SMB model is used, and if so details of this model, such as its resolution End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.basal.bedrock') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Ice --> Mass Balance --> Basal Description of basal melting 7.1. Bedrock Is Required: FALSE    Type: STRING    Cardinality: 0.1 Describe the implementation of basal melting over bedrock End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.basal.ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Ocean Is Required: FALSE    Type: STRING    Cardinality: 0.1 Describe the implementation of basal melting over the ocean End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.frontal.calving') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Ice --> Mass Balance --> Frontal Description of claving/melting from the ice shelf front 8.1. Calving Is Required: FALSE    Type: STRING    Cardinality: 0.1 Describe the implementation of calving from the front of the ice shelf End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.frontal.melting') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.2. Melting Is Required: FALSE    Type: STRING    Cardinality: 0.1 Describe the implementation of melting from the front of the ice shelf End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Ice --> Dynamics ** 9.1. Description Is Required: TRUE    Type: STRING    Cardinality: 1.1 General description if ice sheet and ice shelf dynamics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.approximation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "SIA" # "SAA" # "full stokes" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 9.2. Approximation Is Required: TRUE    Type: ENUM    Cardinality: 1.N Approximation type used in modelling ice dynamics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.adaptive_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 9.3. Adaptive Timestep Is Required: TRUE    Type: BOOLEAN    Cardinality: 1.1 Is there an adaptive time scheme for the ice scheme? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 9.4. Timestep Is Required: TRUE    Type: INTEGER    Cardinality: 1.1 Timestep (in seconds) of the ice scheme. If the timestep is adaptive, then state a representative timestep. End of explanation """
phanrahan/magmathon
notebooks/tutorial/coreir/coreir-tutorial/full_adder.ipynb
mit
import magma as m import mantle """ Explanation: FullAdder - Combinational Circuits This notebook walks through the implementation of a basic combinational circuit, a full adder. This example introduces many of the features of Magma including circuits, wiring, operators, and the type system. Start by importing Magma and Mantle. Magma is the core system which implements circuits and the methods to compose them, and Mantle is a library of useful circuits. End of explanation """ def fulladder(A, B, C): return A^B^C, A&B|B&C|C&A # sum, carry """ Explanation: A full adder has three single bit inputs, and returns the sum and the carry. The sum is the exclusive or of the 3 bits, the carry is 1 if any two of the inputs bits are 1. Here is a schematic of a full adder circuit (from logisim). We start by defining a Python function that implements a full adder. The full adder function takes three single bit inputs and returns two outputs as a tuple. The first element of tuple is the sum, the second element is the carry. We compute the sum and carry using standard Python bitwise operators &amp;, |, and ^. End of explanation """ assert fulladder(1, 0, 0) == (1, 0), "Failed" assert fulladder(0, 1, 0) == (1, 0), "Failed" assert fulladder(1, 1, 0) == (0, 1), "Failed" assert fulladder(1, 0, 1) == (0, 1), "Failed" assert fulladder(1, 1, 1) == (1, 1), "Failed" print("Success!") """ Explanation: We can test our Python function to verify that our implementation behaves as expected. We'll use the standard Python assert pattern. End of explanation """ class FullAdder(m.Circuit): name = "FullAdderExample" IO = ["I0", m.In(m.Bit), "I1", m.In(m.Bit), "CIN", m.In(m.Bit), "O", m.Out(m.Bit), "COUT", m.Out(m.Bit)] @classmethod def definition(io): O, COUT = fulladder(io.I0, io.I1, io.CIN) io.O <= O io.COUT <= COUT """ Explanation: Now that we have an implementation of fulladder as a Python function, we'll use it to construct a Magma Circuit. A Circuit in Magma corresponds to a module in verilog. End of explanation """ from magma.simulator import PythonSimulator fulladder_magma = PythonSimulator(FullAdder) assert fulladder_magma(1, 0, 0) == fulladder(1, 0, 0), "Failed" assert fulladder_magma(0, 1, 0) == fulladder(0, 1, 0), "Failed" assert fulladder_magma(1, 1, 0) == fulladder(1, 1, 0), "Failed" assert fulladder_magma(1, 0, 1) == fulladder(1, 0, 1), "Failed" assert fulladder_magma(1, 1, 1) == fulladder(1, 1, 1), "Failed" print("Success!") """ Explanation: First, notice that the FullAdder is a subclass of Circuit. All Magma circuits are classes in python. Second, the attribute IO defines the interface to the circuit. IO is a list of alternating keys and values. The key is the name of the argument, and the value is the type. In this circuit, all the inputs and outputs have Magma type Bit. We also qualify each type as an input or an output using the functions In and Out. Third, we provide a function definition. definition must be a class method and this is indicated with the decorator @classmethod. The purpose of the definition function is to create the actual full adder circuit. The arguments are passed to definition as the object io. This object has fields for each argument in the interface. The body of definition calls our previously defined python function fulladder. Note that when we call the python function fulladder inside definition it is passed Magma values not standard python values. When we tested fulladder sbove we called it with ints. When we called it inside definition the values passed to the Python fulladder function are Magma values of type Bit. The Python bitwise operators are overloaded to compute logical functions of the Magma values (this corresponds to constructing the circuits to compute logical functions and, or, and xor, and wiring inputs to outputs). fulladder returns two values. These values are assigned to the python variables O and COUT. Remember that assigning to a Python variable sets the variable to refer to the object. Magma values are Python objects, so assigning an object to a variable creates a reference to that Magma value. In order to complete the definition of the circuit, O and COUT need to be wired to the outputs in the interface. The python &lt;= operator is overloaded to perform wiring. Next we simulate the circuit and compare the results to the python function fulladder. End of explanation """ from magma.waveform import waveform test_vectors_raw = [ [0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 0, 1], [1, 0, 0, 1, 0], [1, 0, 1, 0, 1], [1, 1, 0, 0, 1], [1, 1, 1, 1, 1] ] waveform(test_vectors_raw, ["a", "b", "cin", "sum", "cout"]) """ Explanation: Here is another way to test the circuit. We define a set of test vectors and plot them in python. End of explanation """ from fault.test_vectors import generate_simulator_test_vectors from bit_vector import BitVector test_vectors = [ [BitVector(x) for x in test_vector] for test_vector in test_vectors_raw ] tests = generate_simulator_test_vectors(FullAdder, flatten=False) """ Explanation: We can use the simulator to also generate a set of test vectors. End of explanation """ print( "Success" if tests == test_vectors else "Failure" ) """ Explanation: Finally, compare the simulated test vectors to the expected values. End of explanation """ m.compile("build/FullAdder", FullAdder, output="coreir") %cat build/FullAdder.json m.compile("build/FullAdder", FullAdder, output="coreir-verilog") %cat build/FullAdder.v """ Explanation: The last step we will do is generate coreir and verilog for the full adder circuit. End of explanation """
jpn--/larch
book/example/legacy/300L_itinerary.ipynb
gpl-3.0
import larch, pandas, os, gzip larch.__version__ """ Explanation: 300L: Itinerary Choice Data End of explanation """ from larch.data_warehouse import example_file with gzip.open(example_file("arc"), 'rt') as previewfile: print(*(next(previewfile) for x in range(70))) """ Explanation: The example itinerary choice described here is based on data derived from a ticketing database provided by the Airlines Reporting Corporation. The data represent ten origin destination pairs for travel in U.S. continental markets in May of 2013. Itinerary characteristics have been masked, e.g., carriers are labeled generically as "carrier X" and departure times have been aggregated into categories. A fare is provided but is not completely accurate (a random error has been added to each fare). These modifications were made to satisfy nondisclosure agreements, so that the data can be published freely for teaching and demostration purposes. It is generally representative of real itinerary choice data used in practice, and the results obtained from this data are intuitive from a behavioral perspective, but it is not quite accurate and should not be used for behavioral studies. End of explanation """ itin = pandas.read_csv(example_file("arc"), index_col=['id_case','id_alt']) itin.info() itin.head() d = larch.DataFrames(itin, ch='choice', crack=True, autoscale_weights=True) d.info(1) """ Explanation: The first line of the file contains column headers. After that, each line represents an alternative available to one or more decision makers. In our sample data, we see the first 67 lines of data share a id_case of 1, indicating that they are 67 different itineraries available to the first decision maker type. An identidier of the alternatives is given by the number in the column id_alt, although this number is simply a sequential counter within each case in the raw data, and conveys no other information about the itinerary or its attributes. The observed choices of the decision maker[s] are indicated in the column choice. That column counts the number of travelers who face this choice set and chose the itinerary described by this row in the file. We can load this data easily using pandas. We'll also set the index of the resulting DataFrame to be the case and alt identifiers. End of explanation """
tkarna/cofs
demos/02-2d-tsunami.ipynb
mit
%matplotlib inline import matplotlib import matplotlib.pyplot as plt import scipy.interpolate # used for interpolation import pyproj # used for coordinate transformations import math from thetis import * """ Explanation: Simulating the 1945 Makran Tsunami using Thetis The 1945 Makran Tsunami was a large tsunami which originated due to the 1945 Balochistan earthquake. The resulting tsunami is beielved to have killed around 4000 people along the coast of modern day Pakistan, India, Iran and Oman. Tidal records indicate that the tsunami was recorded as far as the islands of Seychells and Minicoy. Moden simulations of the tsunami indicate tsunami elevations would have been observed across the islands of the Maldives as well. Here we will model the tsunami using elevations from actual fault estimations. <img src="figures/Map_of_region.png" style="height:1000px, width:1000px"> As usual we begin by importing the required python libraries and modules. End of explanation """ mesh = Mesh('runfiles/mesh.msh') plt.figure(figsize=(12, 8)) ax = plt.gca() triplot(mesh, axes=ax); """ Explanation: Importing the mesh Next we will import the mesh (this mesh was actually created using qmesh mentioned in yesterday's lecture). Additionally we will visualise the mesh as well using the firedrake plot utility function. The plot function provides an easy way to plot of firedrake functions. End of explanation """ P1 = FunctionSpace(mesh, "CG", 1) bathymetry_2d = Function(P1, name='Bathymetry') depth = 2000.0 bathymetry_2d.assign(depth) tricontourf(bathymetry_2d); """ Explanation: The mesh is created using a UTM-based coordinate system, which divides the world in different zones. In each zone coordinates can be accurately represented by a flat x,y plane. The zone that covers our region is UTM zone 43 which is valid between 72 and 78 degrees longitude East. Setup the bathymetry Next we will define a bathymetry function. For the purpose of this simulation to keeps things simple we will assign a constant depth of 20m. Before creating the bathymetry function and assigning depth we will visualise the bathymetry of the area using the GEBCO bathymetry dataset. <img src="figures/Depth.png" style="height:1000px, width:1000px"> To start of with however, we will simply use a constant depth of 2000m. The bathymetry function will be defined within the function space of piecewise linear functions ("CG" for Continous Galerkin and a polynomial degree of 1). We will again visualise the depth to confirm if the value is assigned across the domain. End of explanation """ init_elev = Function(P1, name = 'init_elev') """ Explanation: Initial Elevation Now we will define a function for the initial elevation, using the same P1 function space. This initial elevation function will set the values for the initial elevation in our simulation. It contains a perturbation in the North of the domain that represent the initial stage of a tsunami. End of explanation """ mesh_coordinates = mesh.coordinates.dat.data init_elev_data = init_elev.dat.data """ Explanation: After defining the initial elevation function we need to set the values of the function, across our mesh. The initial elevation is given to us stored on a regular lon, lat grid. In our simulation we will be using a mesh defined in UTM zone 43 coordinates, and thus we need to perform a coordinate transformation and interpolate between the two grids. First we extract the coordinates of the mesh (in UTM zone 43) and the values of the initial value function as numpy arrays: End of explanation """ data = np.genfromtxt('runfiles/outputs.txt') print (np.round(data[0],5)) """ Explanation: Next we will import the data that we wish to be interpolate onto the initial elevation function. Here the data that we wish to be interpolated on to our elevation function is the vertical displacement of the free-surface due to the earthquake. Given the earthquake fault parameters which are available from various sources such as USGS these deformations can be obtained through various means. Here we will use the output obtained from an 'Okada model' utilising single-fault parameters as provided in Arjun.et.al. We also print the first row of the data, the columns are arranged as Longitude, Latitude, x, y and z displacement. End of explanation """ intp = scipy.interpolate.NearestNDInterpolator(data[:,0:2], data[:,4]) """ Explanation: In order to interpolate the data values onto our mesh, we will use a nearest-neighbour interpolator from scipy. We extract the first two columns (lon and lat) as the coordinates, and the fourth column (vertical displacement) as the values we want to interpolate: End of explanation """ outproj = pyproj.Proj(init='epsg:4326') inproj = pyproj.Proj(init='epsg:32643') lon, lat = pyproj.transform(inproj, outproj, mesh_coordinates[:,0], mesh_coordinates[:,1]) """ Explanation: intp is now an interpolator object that can interpolate the data at any location using intp(lon, lat). However since our mesh is in Universal Transverse Mercator coordinate system (UTM) coordinates, we first convert the coordinates of the mesh points into lat, lon. This is done using the pyproj library: End of explanation """ init_elev_data[:] = intp(lon, lat) """ Explanation: lon and lat are now two numpy arrays with longitude and latitude of all mesh points. These can be fed straight into intp to return an array of the interpolated values in these points. By assigning it to the init_elev_data array these will become the values of the init_elev function. End of explanation """ plt.figure(figsize=(12, 8)) ax = plt.gca() tricontourf(init_elev, axes=ax, cmap=matplotlib.cm.coolwarm, levels=50); """ Explanation: Let's plot this to check: End of explanation """ solver_obj = solver2d.FlowSolver2d(mesh, bathymetry_2d) options = solver_obj.options # total duration in seconds options.simulation_export_time = 900.0 # export interval in seconds options.simulation_end_time = 3600.0 * 2 options.timestepper_type = 'CrankNicolson' options.timestep = 5.0 options.output_directory = 'outputs_makran_tsunami' options.fields_to_export = [] options.fields_to_export_hdf5 = ['elev_2d', 'uv_2d'] """ Explanation: Setting Solver Options Now we have everything we need to setup the solver and set its options. The setup is very similar to what was discussed for the 2D channel example. End of explanation """ solver_obj.bnd_functions['shallow_water'] = { 100: {'un': 0.0}, 200: {'un': 0.0, 'elev' :0.0} } """ Explanation: Boundary and Initial Conditions Next we define the boundary conditions of our model. We will set the velocities at the coastlines and open boundaries to zero. At the open boundaries we set both the normal velocity and elevation to zero, this leads to weakly reflective boundaries. End of explanation """ solver_obj.assign_initial_conditions(elev=init_elev) """ Explanation: Additionaly we set the initial conditions for our simulation. Here we use the init_elev we set up above. Initial velocities are zero (by default): End of explanation """ solver_obj.iterate() elev = Function(solver_obj.function_spaces.H_2d, name='elev_2d') uv = Function(solver_obj.function_spaces.U_2d, name='uv_2d') last_idx = solver_obj.i_export nrows = math.ceil(last_idx/2) fig, axes = plt.subplots(nrows, 2, figsize=(16, 6*nrows)) for idx, ax in enumerate(axes.flatten()): filename = os.path.join(options.output_directory, 'hdf5','Elevation2d_%05d' % idx) dc = DumbCheckpoint(filename, mode=FILE_READ) dc.load(elev) dc.close() # by specifying cmap=None above, we avoid displaying a colorbar tricontourf(elev, axes=ax, cmap=matplotlib.cm.coolwarm, levels=50) # Firedrake sets an automatic colorbar range which therefore changes per timestep # instead, we want to fix it: cbar = ax.collections[-1].set_clim(-5, 5) # we do want to set an appropriate colormap cbar = ax.collections[-1].set_cmap(matplotlib.cm.coolwarm) ax.axis('equal') ax.title.set_text('Export no. %d at t=%.0f' % (idx, options.simulation_export_time*idx)) plt.tight_layout() """ Explanation: Now set the solver iterator to start the simulation running. Note that since we do not have any time varying forcing, we do not need a update_forcings function. End of explanation """ dc = DumbCheckpoint('runfiles/bathy', mode=FILE_READ) dc.load(bathymetry_2d, name='bathy'); """ Explanation: Further Practice a. Instead of the constant bathymetry, load the bathymetry file provided in the runfiles folder, visuallize the bathymetry and use this bathymetry to run the model. Notice any difference? Hint, to load the bathymetry, use: End of explanation """
econ-ark/HARK
examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb
apache-2.0
# This cell has a bit of initial setup. You can click the triangle to the left to expand it. # Click the "Run" button immediately above the notebook in order to execute the contents of any cell # WARNING: Each cell in the notebook relies upon results generated by previous cells # The most common problem beginners have is to execute a cell before all its predecessors # If you do this, you can restart the kernel (see the "Kernel" menu above) and start over import matplotlib.pyplot as plt import numpy as np import HARK from copy import deepcopy mystr = lambda number : "{:.4f}".format(number) from HARK.utilities import plot_funcs """ Explanation: A Gentle Introduction to HARK This notebook provides a simple, hands-on tutorial for first time HARK users -- and potentially first time Python users. It does not go "into the weeds" - we have hidden some code cells that do boring things that you don't need to digest on your first experience with HARK. Our aim is to convey a feel for how the toolkit works. For readers for whom this is your very first experience with Python, we have put important Python concepts in boldface. For those for whom this is the first time they have used a Jupyter notebook, we have put Jupyter instructions in italics. Only cursory definitions (if any) are provided here. If you want to learn more, there are many online Python and Jupyter tutorials. End of explanation """ from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType """ Explanation: Your First HARK Model: Perfect Foresight We start with almost the simplest possible consumption model: A consumer with CRRA utility \begin{equation} U(C) = \frac{C^{1-\rho}}{1-\rho} \end{equation} has perfect foresight about everything except the (stochastic) date of death, which occurs with constant probability implying a "survival probability" $\newcommand{\LivPrb}{\aleph}\LivPrb < 1$. Permanent labor income $P_t$ grows from period to period by a factor $\Gamma_t$. At the beginning of each period $t$, the consumer has some amount of market resources $M_t$ (which includes both market wealth and currrent income) and must choose how much of those resources to consume $C_t$ and how much to retain in a riskless asset $A_t$ which will earn return factor $R$. The agent's flow of utility $U(C_t)$ from consumption is geometrically discounted by factor $\beta$. Between periods, the agent dies with probability $\mathsf{D}_t$, ending his problem. The agent's problem can be written in Bellman form as: \begin{eqnarray} V_t(M_t,P_t) &=& \max_{C_t}~U(C_t) + \beta \aleph V_{t+1}(M_{t+1},P_{t+1}), \ & s.t. & \ %A_t &=& M_t - C_t, \ M_{t+1} &=& R (M_{t}-C_{t}) + Y_{t+1}, \ P_{t+1} &=& \Gamma_{t+1} P_t, \ \end{eqnarray} A particular perfect foresight agent's problem can be characterized by values of risk aversion $\rho$, discount factor $\beta$, and return factor $R$, along with sequences of income growth factors ${ \Gamma_t }$ and survival probabilities ${\mathsf{\aleph}_t}$. To keep things simple, let's forget about "sequences" of income growth and mortality, and just think about an $\textit{infinite horizon}$ consumer with constant income growth and survival probability. Representing Agents in HARK HARK represents agents solving this type of problem as $\textbf{instances}$ of the $\textbf{class}$ $\texttt{PerfForesightConsumerType}$, a $\textbf{subclass}$ of $\texttt{AgentType}$. To make agents of this class, we must import the class itself into our workspace. (Run the cell below in order to do this). End of explanation """ # This cell defines a parameter dictionary. You can expand it if you want to see what that looks like. PF_dictionary = { 'CRRA' : 2.5, 'DiscFac' : 0.96, 'Rfree' : 1.03, 'LivPrb' : [0.98], 'PermGroFac' : [1.01], 'T_cycle' : 1, 'cycles' : 0, 'AgentCount' : 10000 } # To those curious enough to open this hidden cell, you might notice that we defined # a few extra parameters in that dictionary: T_cycle, cycles, and AgentCount. Don't # worry about these for now. """ Explanation: The $\texttt{PerfForesightConsumerType}$ class contains within itself the python code that constructs the solution for the perfect foresight model we are studying here, as specifically articulated in these lecture notes. To create an instance of $\texttt{PerfForesightConsumerType}$, we simply call the class as if it were a function, passing as arguments the specific parameter values we want it to have. In the hidden cell below, we define a $\textbf{dictionary}$ named $\texttt{PF_dictionary}$ with these parameter values: | Param | Description | Code | Value | | :---: | --- | --- | :---: | | $\rho$ | Relative risk aversion | $\texttt{CRRA}$ | 2.5 | | $\beta$ | Discount factor | $\texttt{DiscFac}$ | 0.96 | | $R$ | Risk free interest factor | $\texttt{Rfree}$ | 1.03 | | $\aleph$ | Survival probability | $\texttt{LivPrb}$ | 0.98 | | $\Gamma$ | Income growth factor | $\texttt{PermGroFac}$ | 1.01 | For now, don't worry about the specifics of dictionaries. All you need to know is that a dictionary lets us pass many arguments wrapped up in one simple data structure. End of explanation """ PFexample = PerfForesightConsumerType(**PF_dictionary) # the asterisks ** basically say "here come some arguments" to PerfForesightConsumerType """ Explanation: Let's make an object named $\texttt{PFexample}$ which is an instance of the $\texttt{PerfForesightConsumerType}$ class. The object $\texttt{PFexample}$ will bundle together the abstract mathematical description of the solution embodied in $\texttt{PerfForesightConsumerType}$, and the specific set of parameter values defined in $\texttt{PF_dictionary}$. Such a bundle is created passing $\texttt{PF_dictionary}$ to the class $\texttt{PerfForesightConsumerType}$: End of explanation """ PFexample.solve() """ Explanation: In $\texttt{PFexample}$, we now have defined the problem of a particular infinite horizon perfect foresight consumer who knows how to solve this problem. Solving an Agent's Problem To tell the agent actually to solve the problem, we call the agent's $\texttt{solve}$ method. (A method is essentially a function that an object runs that affects the object's own internal characteristics -- in this case, the method adds the consumption function to the contents of $\texttt{PFexample}$.) The cell below calls the $\texttt{solve}$ method for $\texttt{PFexample}$ End of explanation """ PFexample.solution[0].cFunc """ Explanation: Running the $\texttt{solve}$ method creates the attribute of $\texttt{PFexample}$ named $\texttt{solution}$. In fact, every subclass of $\texttt{AgentType}$ works the same way: The class definition contains the abstract algorithm that knows how to solve the model, but to obtain the particular solution for a specific instance (paramterization/configuration), that instance must be instructed to $\texttt{solve()}$ its problem. The $\texttt{solution}$ attribute is always a $\textit{list}$ of solutions to a single period of the problem. In the case of an infinite horizon model like the one here, there is just one element in that list -- the solution to all periods of the infinite horizon problem. The consumption function stored as the first element (element 0) of the solution list can be retrieved by: End of explanation """ mPlotTop=10 plot_funcs(PFexample.solution[0].cFunc,0.,mPlotTop) """ Explanation: One of the results proven in the associated the lecture notes is that, for the specific problem defined above, there is a solution in which the ratio $c = C/P$ is a linear function of the ratio of market resources to permanent income, $m = M/P$. This is why $\texttt{cFunc}$ can be represented by a linear interpolation. It can be plotted between an $m$ ratio of 0 and 10 using the command below. End of explanation """ humanWealth = PFexample.solution[0].hNrm mMinimum = PFexample.solution[0].mNrmMin print("This agent's human wealth is " + str(humanWealth) + ' times his current income level.') print("This agent's consumption function is defined (consumption is positive) down to m_t = " + str(mMinimum)) """ Explanation: The figure illustrates one of the surprising features of the perfect foresight model: A person with zero money should be spending at a rate more than double their income (that is, $\texttt{cFunc}(0.) \approx 2.08$ - the intersection on the vertical axis). How can this be? The answer is that we have not incorporated any constraint that would prevent the agent from borrowing against the entire PDV of future earnings-- human wealth. How much is that? What's the minimum value of $m_t$ where the consumption function is defined? We can check by retrieving the $\texttt{hNrm}$ attribute of the solution, which calculates the value of human wealth normalized by permanent income: End of explanation """ plot_funcs(PFexample.solution[0].cFunc, mMinimum, mPlotTop) """ Explanation: Yikes! Let's take a look at the bottom of the consumption function. In the cell below, the bounds of the plot_funcs function are set to display down to the lowest defined value of the consumption function. End of explanation """ NewExample = deepcopy(PFexample) """ Explanation: Changing Agent Parameters Suppose you wanted to change one (or more) of the parameters of the agent's problem and see what that does. We want to compare consumption functions before and after we change parameters, so let's make a new instance of $\texttt{PerfForesightConsumerType}$ by copying $\texttt{PFexample}$. End of explanation """ NewExample.assign_parameters(DiscFac = 0.90) NewExample.solve() mPlotBottom = mMinimum plot_funcs([PFexample.solution[0].cFunc, NewExample.solution[0].cFunc], mPlotBottom, mPlotTop) """ Explanation: You can assign new parameters to an AgentType with the assign_parameter method. For example, we could make the new agent less patient: End of explanation """ # Revert NewExample's discount factor and make his future income minuscule # print("your lines here") # Compare the old and new consumption functions plot_funcs([PFexample.solution[0].cFunc,NewExample.solution[0].cFunc],0.,10.) """ Explanation: (Note that you can pass a list of functions to plot_funcs as the first argument rather than just a single function. Lists are written inside of [square brackets].) Let's try to deal with the "problem" of massive human wealth by making another consumer who has essentially no future income. We can virtually eliminate human wealth by making the permanent income growth factor $\textit{very}$ small. In $\texttt{PFexample}$, the agent's income grew by 1 percent per period -- his $\texttt{PermGroFac}$ took the value 1.01. What if our new agent had a growth factor of 0.01 -- his income shrinks by 99 percent each period? In the cell below, set $\texttt{NewExample}$'s discount factor back to its original value, then set its $\texttt{PermGroFac}$ attribute so that the growth factor is 0.01 each period. Important: Recall that the model at the top of this document said that an agent's problem is characterized by a sequence of income growth factors, but we tabled that concept. Because $\texttt{PerfForesightConsumerType}$ treats $\texttt{PermGroFac}$ as a time-varying attribute, it must be specified as a list (with a single element in this case). End of explanation """ # This cell defines a parameter dictionary for making an instance of IndShockConsumerType. IndShockDictionary = { 'CRRA': 2.5, # The dictionary includes our original parameters... 'Rfree': 1.03, 'DiscFac': 0.96, 'LivPrb': [0.98], 'PermGroFac': [1.01], 'PermShkStd': [0.1], # ... and the new parameters for constructing the income process. 'PermShkCount': 7, 'TranShkStd': [0.1], 'TranShkCount': 7, 'UnempPrb': 0.05, 'IncUnemp': 0.3, 'BoroCnstArt': 0.0, 'aXtraMin': 0.001, # aXtra parameters specify how to construct the grid of assets. 'aXtraMax': 50., # Don't worry about these for now 'aXtraNestFac': 3, 'aXtraCount': 48, 'aXtraExtra': [None], 'vFuncBool': False, # These booleans indicate whether the value function should be calculated 'CubicBool': False, # and whether to use cubic spline interpolation. You can ignore them. 'aNrmInitMean' : -10., 'aNrmInitStd' : 0.0, # These parameters specify the (log) distribution of normalized assets 'pLvlInitMean' : 0.0, # and permanent income for agents at "birth". They are only relevant in 'pLvlInitStd' : 0.0, # simulation and you don't need to worry about them. 'PermGroFacAgg' : 1.0, 'T_retire': 0, # What's this about retirement? ConsIndShock is set up to be able to 'UnempPrbRet': 0.0, # handle lifecycle models as well as infinite horizon problems. Swapping 'IncUnempRet': 0.0, # out the structure of the income process is easy, but ignore for now. 'T_age' : None, 'T_cycle' : 1, 'cycles' : 0, 'AgentCount': 10000, 'tax_rate':0.0, } # Hey, there's a lot of parameters we didn't tell you about! Yes, but you don't need to # think about them for now. """ Explanation: Now $\texttt{NewExample}$'s consumption function has the same slope (MPC) as $\texttt{PFexample}$, but it emanates from (almost) zero-- he has basically no future income to borrow against! If you'd like, use the cell above to alter $\texttt{NewExample}$'s other attributes (relative risk aversion, etc) and see how the consumption function changes. However, keep in mind that \textit{no solution exists} for some combinations of parameters. HARK should let you know if this is the case if you try to solve such a model. Your Second HARK Model: Adding Income Shocks Linear consumption functions are pretty boring, and you'd be justified in feeling unimpressed if all HARK could do was plot some lines. Let's look at another model that adds two important layers of complexity: income shocks and (artificial) borrowing constraints. Specifically, our new type of consumer receives two income shocks at the beginning of each period: a completely transitory shock $\theta_t$ and a completely permanent shock $\psi_t$. Moreover, lenders will not let the agent borrow money such that his ratio of end-of-period assets $A_t$ to permanent income $P_t$ is less than $\underline{a}$. As with the perfect foresight problem, this model can be framed in terms of normalized variables, e.g. $m_t \equiv M_t/P_t$. (See here for all the theory). \begin{eqnarray} v_t(m_t) &=& \max_{c_t} ~ U(c_t) ~ + \phantom{\LivFac} \beta \mathbb{E} [(\Gamma_{t+1}\psi_{t+1})^{1-\rho} v_{t+1}(m_{t+1}) ], \ a_t &=& m_t - c_t, \ a_t &\geq& \underset{\bar{}}{a}, \ m_{t+1} &=& R/(\Gamma_{t+1} \psi_{t+1}) a_t + \theta_{t+1}, \ \mathbb{E}[\psi]=\mathbb{E}[\theta] &=& 1, \ u(c) &=& \frac{c^{1-\rho}}{1-\rho}. \end{eqnarray} HARK represents agents with this kind of problem as instances of the class $\texttt{IndShockConsumerType}$. To create an $\texttt{IndShockConsumerType}$, we must specify the same set of parameters as for a $\texttt{PerfForesightConsumerType}$, as well as an artificial borrowing constraint $\underline{a}$ and a sequence of income shocks. It's easy enough to pick a borrowing constraint -- say, zero -- but how would we specify the distributions of the shocks? Can't the joint distribution of permanent and transitory shocks be just about anything? Yes, and HARK can handle whatever correlation structure a user might care to specify. However, the default behavior of $\texttt{IndShockConsumerType}$ is that the distribution of permanent income shocks is mean one lognormal, and the distribution of transitory shocks is mean one lognormal augmented with a point mass representing unemployment. The distributions are independent of each other by default, and by default are approximated with $N$ point equiprobable distributions. Let's make an infinite horizon instance of $\texttt{IndShockConsumerType}$ with the same parameters as our original perfect foresight agent, plus the extra parameters to specify the income shock distribution and the artificial borrowing constraint. As before, we'll make a dictionary: | Param | Description | Code | Value | | :---: | --- | --- | :---: | | \underline{a} | Artificial borrowing constraint | $\texttt{BoroCnstArt}$ | 0.0 | | $\sigma_\psi$ | Underlying stdev of permanent income shocks | $\texttt{PermShkStd}$ | 0.1 | | $\sigma_\theta$ | Underlying stdev of transitory income shocks | $\texttt{TranShkStd}$ | 0.1 | | $N_\psi$ | Number of discrete permanent income shocks | $\texttt{PermShkCount}$ | 7 | | $N_\theta$ | Number of discrete transitory income shocks | $\texttt{TranShkCount}$ | 7 | | $\mho$ | Unemployment probability | $\texttt{UnempPrb}$ | 0.05 | | $\underset{\bar{}}{\theta}$ | Transitory shock when unemployed | $\texttt{IncUnemp}$ | 0.3 | End of explanation """ from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType IndShockExample = IndShockConsumerType(**IndShockDictionary) """ Explanation: As before, we need to import the relevant subclass of $\texttt{AgentType}$ into our workspace, then create an instance by passing the dictionary to the class as if the class were a function. End of explanation """ IndShockExample.solve() plot_funcs(IndShockExample.solution[0].cFunc,0.,10.) """ Explanation: Now we can solve our new agent's problem just like before, using the $\texttt{solve}$ method. End of explanation """ OtherExample = deepcopy(IndShockExample) # Make a copy so we can compare consumption functions OtherExample.assign_parameters(PermShkStd = [0.2]) # Double permanent income risk (note that it's a one element list) OtherExample.update_income_process() # Call the method to reconstruct the representation of F_t OtherExample.solve() """ Explanation: Changing Constructed Attributes In the parameter dictionary above, we chose values for HARK to use when constructing its numeric representation of $F_t$, the joint distribution of permanent and transitory income shocks. When $\texttt{IndShockExample}$ was created, those parameters ($\texttt{TranShkStd}$, etc) were used by the constructor or initialization method of $\texttt{IndShockConsumerType}$ to construct an attribute called $\texttt{IncomeDstn}$. Suppose you were interested in changing (say) the amount of permanent income risk. From the section above, you might think that you could simply change the attribute $\texttt{TranShkStd}$, solve the model again, and it would work. That's almost true-- there's one extra step. $\texttt{TranShkStd}$ is a primitive input, but it's not the thing you actually want to change. Changing $\texttt{TranShkStd}$ doesn't actually update the income distribution... unless you tell it to (just like changing an agent's preferences does not change the consumption function that was stored for the old set of parameters -- until you invoke the $\texttt{solve}$ method again). In the cell below, we invoke the method $\texttt{update_income_process}$ so HARK knows to reconstruct the attribute $\texttt{IncomeDstn}$. End of explanation """ # Use the line(s) below to plot the consumptions functions against each other """ Explanation: In the cell below, use your blossoming HARK skills to plot the consumption function for $\texttt{IndShockExample}$ and $\texttt{OtherExample}$ on the same figure. End of explanation """
henchc/EDUC290B
01-Intro-to-Computational-Tools-Python.ipynb
mit
age = 42 first_name = 'Ahmed' """ Explanation: Introduction to Computational Tools and Python This notebook introduces students to popular computational tools used in the Digital Humanities and Social Sciences and the research possibilities they create. It then provides an abbreviated introduction to Python focussing on analysis and preparing for a Twitter data analysis on Day 2. Estimated Time: 180 minutes Topics Covered: - Tools available for researchers interested in computational analyses - Common applications for these tools in research - How these tools fit in to the research workflow - Python fundamentals Parts: - Tools - Common Tasks - Introduction to Python - Variables - Data Types - Strings - Lists <a id=tools></a> Tools Online Point-And-Click Tools - Digital Research Tools - Voyant - TextAnalysisOnline - Textalyser Common Programming Languages for Research and Visualization - <a href="https://en.wikipedia.org/wiki/Python_(programming_language)">Python</a> - <a href="https://en.wikipedia.org/wiki/R_(programming_language)">R</a> - <a href="https://en.wikipedia.org/wiki/Julia_(programming_language)">Julia</a> - <a href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a> - <a href="https://en.wikipedia.org/wiki/Java_(programming_language)">Java</a> Qualitative Data Analysis - NVivo - MaxQDA - Dedoose - Tableau Geospatial Analysis - ArcGIS - GmapGIS - Mapbox <a id=commontasks></a> Common Tasks Data Management - Tabular Data - Numerical Data - Text Data - Storing Data - Archiving Data - Annotating Data Qualitative Analysis - Annotating and aggregating non-numerical data - Visualizing non-numerical data Quantitative Analysis - Counting (words, observations, events, locations, etc.) - Traditional statistical analyses Model Building and Machine Learning - Classification - Regression - Clustering - Topic Modeling - Sentiment Analysis - Text Generation Linguistic Analysis and Natural Language Processing (NLP) - Vocabulary - Chunking - Dependency Parsing - Named Entity Recognition (NER) - Semantic Distance Visualization - Graphs and Charts - Network Analysis - Geospatial Analysis Pedagogy - Digital Editions - Much of Visualization <a id=introtopython></a> Introduction to Python <a id=variables></a> Variables Variables are names for values. In Python the = symbol assigns the value on the right to the name on the left. The variable is created when a value is assigned to it. Here's Python code that assigns an age to a variable age and a name in quotation marks to a variable first_name. End of explanation """ print(first_name, 'is', age, 'years old') """ Explanation: Variable names: cannot start with a digit cannot contain spaces, quotation marks, or other punctuation may contain an underscore (typically used to separate words in long variable names) Underscores at the start like __alistairs_real_age have a special meaning so we won't do that until we understand the convention. Use print to display values. Python has a built-in function called print that prints things as text. Call the function (i.e., tell Python to run it) by using its name. Provide values to the function (e.g., things to print) in parentheses. End of explanation """ print(last_name) """ Explanation: print automatically puts a single space between items to separate them. And wraps around to a new line at the end. Variables persist between cells. Variables defined in one cell exist in all following cells. Notebook cells are just a way to organize a program: as far as Python is concerned, all of the source code is one long set of instructions. Variables must be created before they are used. If a variable doesn't exist yet, or if the name has been mis-spelled, Python reports an error. End of explanation """ flabadab = 42 ewr_422_yY = 'Ahmed' print(ewr_422_yY, 'is', flabadab, 'years old') """ Explanation: The last line of an error message is usually the most informative. We will look at error messages in detail later. Python is case-sensitive. Python thinks that upper- and lower-case letters are different, so Name and name are different variables. Again, there are conventions around using upper-case letters at the start of variable names so we will use lower-case letters for now. Use meaningful variable names. Python doesn't care what you call variables as long as they obey the rules (alphanumeric characters and the underscore). End of explanation """ age = age + 3 print('Age in three years:', age) """ Explanation: Use meaningful variable names to help other people understand what the program does. The most important "other person" is your future self. Variables can be used in calculations. We can use variables in calculations just as if they were values. Remember, we assigned 42 to age a few lines ago. End of explanation """ print(type(52)) pi = 3.14159 print(type(pi)) fitness = 'average' print(type(fitness)) """ Explanation: Challenge 1: Making and Printing Variables Make 3 variables: - name (with your full name) - city (where you were born) and - year (when you were born.) Print these three variables so that it prints [your name] was born in [city] in [year]. <a id=datatypes></a> Data Types Every value has a type. Every value in a program has a specific type. Integer (int): counting numbers like 3 or -512. Floating point number (float): fractional numbers like 3.14159 or -2.5. Integers are used to count, floats are used to measure. Character string (usually just called "string", str): text. Written in either single quotes or double quotes (as long as they match). The quotation marks aren't printed when the string is displayed. Use the built-in function type to find the type of a value. Use the built-in function type to find out what type a value has. Works on variables as well. But remember: the value has the type --- the variable is just a label. End of explanation """ print(5 - 3) print('hello' - 'h') """ Explanation: Types control what operations can be done on values. A value's type determines what the program can do to it. End of explanation """ full_name = 'Ahmed' + ' ' + 'Walsh' print(full_name) """ Explanation: Strings can be added and multiplied. "Adding" character strings concatenates them. End of explanation """ separator = '=' * 10 print(separator) """ Explanation: Multiplying a character string by an integer replicates it. Since multiplication is just repeated addition. End of explanation """ print(len(full_name)) """ Explanation: Strings have a length (but numbers don't). The built-in function len counts the number of characters in a string. End of explanation """ print(len(52)) """ Explanation: But numbers don't have a length (not even zero). End of explanation """ print(1 + '2') """ Explanation: Must convert numbers to strings or vice versa when operating on them. Cannot add numbers and strings. End of explanation """ print(1 + int('2')) print(str(1) + '2') """ Explanation: Not allowed because it's ambiguous: should 1 + '2' be 3 or '12'? Use the name of a type as a function to convert a value to that type. End of explanation """ print('half is', 1 / 2.0) print('three squared is', 3.0 ** 2) """ Explanation: Can mix integers and floats freely in operations. Integers and floating-point numbers can be mixed in arithmetic. Python automatically converts integers to floats as needed. End of explanation """ first = 1 second = 5 * first first = 2 print('first is', first, 'and second is', second) """ Explanation: Variables only change value when something is assigned to them. If we make one cell in a spreadsheet depend on another, and update the latter, the former updates automatically. This does not happen in programming languages. End of explanation """ first_name = "Johan" last_name = "Gambolputty" full_name = first_name + last_name print(full_name) """ Explanation: The computer reads the value of first when doing the multiplication, creates a new value, and assigns it to second. After that, second does not remember where it came from. The computer reads the value of first when doing the multiplication, creates a new value, and assigns it to second. After that, second does not remember where it came from. Challenge 2: Making and Coercing Variables Make a variable year and assign it as the year you were born Coerce that variable to a float, and assign it to a new variable year_float Coerce year_float to a string, and assign it to a new variable year_string Someone in your class says they were born in 1997. Really? Really. Find out what your age difference is, using only year_string. <a id=strings></a> Strings We can do things with strings We've already seen some operations that can be done with strings. End of explanation """ full_name = first_name + " " + last_name print(full_name) """ Explanation: Remember that computers don't understand context. End of explanation """ full_name[1] """ Explanation: Strings are made up of sub-strings You can think of strings as a sequence of smaller strings or characters. We can access a piece of that sequence using []. End of explanation """ full_name[0] full_name[4] """ Explanation: Gotcha - Python (and many other langauges) start counting from 0. End of explanation """ full_name[0:4] full_name[0:5] """ Explanation: You can splice strings using [ : ] if you want a range (or "slice") of a sequence, you get everything before the second index: End of explanation """ full_name[:5] full_name[5:] """ Explanation: You can see some of the logic for this when we consider implicit indices. End of explanation """ str. """ Explanation: String Have Methods There are other operations defined on string data. These are called string methods. IPython lets you do tab-completion after a dot ('.') to see what methods an object (i.e., a defined variable) has to offer. Try it now! End of explanation """ str.upper? """ Explanation: Let's look at the upper method. What does it do? Lets take a look at the documentation. IPython lets us do this with a question mark ('?') before or after an object (again, a defined variable). End of explanation """ full_name.upper() """ Explanation: So we can use it to upper-caseify a string. End of explanation """ print(full_name) full_name = full_name.upper() print(full_name) """ Explanation: You have to use the parenthesis at the end because upper is a method of the string class. Don't forget, simply calling the method does not change the original variable, you must reassign the variable: End of explanation """ "Johann Gambolputty".upper() """ Explanation: For what its worth, you don't need to have a variable to use the upper() method, you could use it on the string itself. End of explanation """ tweet = 'RT @JasonBelich: #March4Trump #berkeley elderly man pepper sprayed by #antifa https://t.co/5z3O6UZuhL' """ Explanation: What do you think should happen when you take upper of an int? What about a string representation of an int? Challenge 3: Write your name Make two string variables, one with your first name and one with your last name. Concatenate both strings to form your full name and assign it to a variable. Assign a new variable that has your full name in all upper case. Slice that string to get your first name again. *Challenge 4: Exploring string methods * In our next meeting we will be looking at Twitter activity from the March4Trump event in Berkeley on March 4, 2017. Below was the most retweeted tweet during the March4Trump event. Use this tweet to explore the methods above. End of explanation """ country_list = ["Afghanistan", "Canada", "Sierra Leone", "Denmark", "Japan"] type(country_list) """ Explanation: Using this tweet, try seeing what the following string methods do: * `split` * `join` * `replace` * `strip` * `find` <a id=lists></a> Lists A list is an ordered, indexable collection of data. Lets say you're doing a study on the following countries: country: "Afghanistan" "Canada" "Sierra Leone" "Denmark" "Japan" You could put that data into a list contain data in square brackets [...], each value is separated by a comma ,. End of explanation """ len(country_list) """ Explanation: Use len to find out how many values are in a list. End of explanation """ print('the first item is:', country_list[0]) print('the fourth item is:', country_list[3]) """ Explanation: Use an item’s index to fetch it from a list. Each value in a list is stored in a particular location. Locations are numbered from 0 rather than 1. Use the location’s index in square brackets to access the value it contains. End of explanation """ print(country_list[-1]) print(country_list[-2]) """ Explanation: Lists can be indexed from the back using a negative index. End of explanation """ print(country_list[1:4]) """ Explanation: "Slice" a list using [ : ] Just as with strings, we can get multiple items from a list using splicing Note that the first index is included, while the second is excluded End of explanation """ print(country_list[:4]) print(country_list[2:]) """ Explanation: Leave an index blank to get everything from the beginning / end End of explanation """ country_list[0] = "Iran" print('Country List is now:', country_list) """ Explanation: Lists’ values can be replaced by assigning to specific indices. End of explanation """ mystring = "Donut" mystring[0] = 'C' """ Explanation: This makes lists different from strings. You cannot change the characters in a string after it has been created. Immutable: cannot be changed after creation. In contrast, lists are mutable: they can be modified in place. End of explanation """ country_list. """ Explanation: Lists have Methods Just like strings have methods, lists do too. Remember that a method is like a function, but tied to a particular object. Use object_name.method_name to call methods. IPython lets us do tab completion after a dot ('.') to see what an object has to offer. End of explanation """ country_list.append("United States") print(country_list) """ Explanation: If you want to append items to the end of a list, use the append method. End of explanation """ print("original list was:", country_list) del country_list[3] print("the list is now:", country_list) """ Explanation: Use del to remove items from a list entirely. del list_name[index] removes an item from a list and shortens the list. Not a function or a method, but a statement in the language. End of explanation """ complex_list = ['life', 42, 'the universe', [1,2,3]] print(complex_list) """ Explanation: Lists may contain values of different types. A single list may contain numbers, strings, and anything else. End of explanation """ print(complex_list[3]) print(complex_list[3][0]) """ Explanation: Notice that we put a list inside of a list, which can itself be indexed. The same could be done for a string. End of explanation """ print(country_list[99]) """ Explanation: The empty list contains no values. Use [] on its own to represent a list that doesn't contain any values. "The zero of lists." Helpful as a starting point for collecting values (which we will see in the next episode.) Indexing beyond the end of the collection is an error. Python reports an IndexError if we attempt to access a value that doesn't exist. This is a kind of runtime error. Cannot be detected as the code is parsed because the index might be calculated based on data. End of explanation """ hashtags = ['#March4Trump', '#Fascism', '#TwitterIsFascist', '#majority', '#CouldntEvenStopDeVos', '#IsTrumpCompromised', '#Berkeley', '#NotMyPresident', '#mondaymotivation', '#BlueLivesMatter', '#Action4Trump', '#impeachtrump' '#Periscope', '#march', '#TrumpRussia', '#obamagate', '#Resist', '#sedition', '#NeverTrump', '#maga'] print(hashtags[::2]) print() print(hashtags[::-1]) """ Explanation: Challenge 5: Exploring Lists What does the following program print? End of explanation """ str.join? """ Explanation: How long is the hashtags list? Use the .index() method to find out what the index number is for #Resist: Read the help file (or the Python documentation) for join(), a string method. End of explanation """
Vvkmnn/books
AutomateTheBoringStuffWithPython/lesson41.ipynb
gpl-3.0
from selenium import webdriver """ Explanation: Lesson 41: Controlling the Browser with the Selenium Module We download and parse webpages using beautifulsoup module, but some pages require logins and other dependencies to function properly. We can simulate these effects using selenium to launch a programmatic browser. The course uses Firefox, but we will be using Google Chrome. End of explanation """ browser = webdriver.Chrome() """ Explanation: The webdriver.Chrome() command launches an interactive browser using selenium. All commands referencing this new browser variable will use this specific browser window. There are a variety of browsers available, they just need to be installed. End of explanation """ browser.get('https://automatetheboringstuff.com') """ Explanation: We can then use commands like browser.get() to load urls: End of explanation """ elem = browser.find_element_by_css_selector('#post-6 > div > ol:nth-child(20) > li:nth-child(1) > a') """ Explanation: We can now use CSS selectors to interact with specific elements on this page; you can find them in Chrome using the Developer tools: This web element is then referenced using the browser method find_element_by_css_selector. There are a variety of other find methods, which can reference names, classes, tags, etc. End of explanation """ # Clicks on that first link elem.click() """ Explanation: Once selected, we can a run a .click() method on that element to interact with the selected web element. End of explanation """ # Find all paragraph elements on the current page in the browser (Introduction) elems = browser.find_elements_by_css_selector('p') elems """ Explanation: We can also select multiple elements on a webpage and storing them in a list using the find_elements_by method instead of find_element_by. End of explanation """ # Element by class name example searchElem = browser.find_element_by_class_name('search-field') """ Explanation: There are many ways to use the webdriver to find elements, and they are summarized here. There are also ways to interact with a webpage, and input our own text as necessary. Let use the search box of the Automate website as the example: End of explanation """ # Send the text 'zophie' to the Search element searchElem.send_keys('zophie') # Submit that element, if available searchElem.submit() #Clear any existing text sent to the element using 'Ctrl+A' and a new string; otherwise `send_keys` will just append it #searchElem.sendKeys(Keys.chord(Keys.CONTROL, "a"), "zophie"); """ Explanation: We can use the .send_keys method to pass text to this element, and then submit via the form type of that element. End of explanation """ browser.back() browser.forward() browser.refresh() """ Explanation: We can also use browser functions themselves programmatically, including functions like 'back', 'forward', 'refresh', etc. End of explanation """ browser.quit() """ Explanation: We can also quit the entire browser with .quit(). End of explanation """ browser = webdriver.Chrome() browser.get('https://automatetheboringstuff.com') elem = browser.find_element_by_css_selector('#post-6 > div > p:nth-child(6)') """ Explanation: We can also use Python scripts to read the content via the selenium browser. End of explanation """ elem.text """ Explanation: All web elements have a .text() variable that stores all text of the element. End of explanation """ bodyElem = browser.find_element_by_css_selector('html') print(bodyElem.text) """ Explanation: Similarly, we can select all text on the webpage via the &lt;html&gt; or &lt;body&gt; element, which should include all text on the page, since &lt;html&gt; is the first element on any webpage. End of explanation """
sz-workshop-2017/virtual-machine
notebooks/4.1 - Working with NLTK.ipynb
apache-2.0
# First we import the NLTK library and download # the data used in the examples in the book # the data will be stored in a directory on the # virtual machine but accessible through your notebooks import nltk nltk.download() from nltk.book import * """ Explanation: 4.1 - Working with NLTK In this notebook we will work through some of the initial examples in the NLTK book written by Steven Bird, Ewan Klein, and Edward Loper. You can follow along by going to the first chapter of the book: http://www.nltk.org/book/ch01.html 1.2 Getting Started with NLTK End of explanation """ text5.concordance("lol") text1.similar("monstrous") text2.common_contexts(["monstrous", "very"]) text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"]) """ Explanation: 1.3 Searching Text End of explanation """ print('number of words:', len(text3)) sorted(set(text3))[:20] len(set(text3)) len(set(text3)) / len(text3) text3.count("smote") 100 * text4.count('a') / len(text4) def lexical_diversity(text): return len(set(text)) / len(text) def percentage(count, total): return 100 * count / total print(lexical_diversity(text3)) print(lexical_diversity(text5)) print(percentage(4, 5)) print(percentage(text4.count('a'), len(text4))) """ Explanation: 1.4 Counting Vocabulary End of explanation """ fdist1 = FreqDist(text1) print(fdist1) fdist1.most_common(50) fdist1.plot(50, cumulative=True) fdist1.hapaxes() """ Explanation: 3.1 Frequency Distributions End of explanation """ V = set(text1) long_words = [w for w in V if len(w) > 12 and fdist1[w] > 7] sorted(long_words) """ Explanation: 3.2 Fine-grained Selection of Words End of explanation """ list(nltk.bigrams(['more', 'is', 'said', 'than', 'done'])) text4.collocations() text8.collocations() """ Explanation: 3.3 Collocations and Bigrams End of explanation """ fdist = FreqDist(len(w) for w in text1) fdist print(fdist.most_common()) print(fdist.max()) print(fdist[3]) print(fdist.freq(3)) tricky = sorted(w for w in set(text2) if 'cie' in w or 'cei' in w) for word in tricky: print(word, end=' ') """ Explanation: 3.3 Counting Other Things End of explanation """
OriHoch/knesset-data-pipelines
jupyter-notebooks/committee meeting attendees.ipynb
mit
import yaml from dataflows import Flow, filter_rows, cache, dump_to_path from datapackage_pipelines_knesset.common_flow import load_knesset_data, load_member_names import tabulator """ Explanation: Example flow for processing and aggregating stats about committee meeting attendees and protocol parts See the DataFlows documentation for more details regarding the Flow object and processing functions. Feel free to modify and commit changes which demonstrate additional functionality or relevant data. Imports End of explanation """ # Limit processing of protocol parts for development PROCESS_PARTS_LIMIT = 500 # Enable caching of protocol parts data (not efficient, should only be used for local development with sensible PROCESS_PARTS_LIMIT) PROCESS_PARTS_CACHE = True # Filter the meetings to be processed, these kwargs are passed along to DataFlows filter_rows processor for meetings resource MEETINGS_FILTER_ROWS_KWARGS = {'equals': [{'KnessetNum': 20}]} # Don'e use local data - loads everything from knesset data remote storage # When set to False - also enables caching, so you won't download from remote storage on 2nd run. USE_DATA = False """ Explanation: Constants End of explanation """ # Loads a dict containing mapping between knesset member id and the member name member_names = load_member_names(use_data=USE_DATA) # define flow steps for loading the source committee meetings data # the actual loading is done later in the Flow load_steps = ( load_knesset_data('people/committees/meeting-attendees/datapackage.json', USE_DATA), filter_rows(**MEETINGS_FILTER_ROWS_KWARGS) ) if not USE_DATA: # when loading from URL - enable caching which will skip loading on 2nd run load_steps = (cache(*load_steps, cache_path='.cache/people-committee-meeting-attendees-knesset-20'),) """ Explanation: Load source data End of explanation """ from collections import defaultdict stats = defaultdict(int) member_attended_meetings = defaultdict(int) def process_meeting_protocol_part(row): stats['processed parts'] += 1 if row['body'] and 'אנחנו ככנסת צריכים להיות ערוכים' in row['body']: stats['meetings contain text: we as knesset need to be prepared'] += 1 def process_meeting(row): stats['total meetings'] += 1 if row['attended_mk_individual_ids']: for mk_id in row['attended_mk_individual_ids']: member_attended_meetings[mk_id] += 1 parts_filename = row['parts_parsed_filename'] if parts_filename: if PROCESS_PARTS_LIMIT and stats['processed parts'] < PROCESS_PARTS_LIMIT: steps = (load_knesset_data('committees/meeting_protocols_parts/' + parts_filename, USE_DATA),) if not USE_DATA and PROCESS_PARTS_CACHE: steps = (cache(*steps, cache_path='.cache/committee-meeting-protocol-parts/' + parts_filename),) steps += (process_meeting_protocol_part,) Flow(*steps).process() process_steps = (process_meeting,) """ Explanation: Inspect the datapackages which will be loaded Last command's output log should contain urls to datapackage.json files, open them and check the table schema to see the resource metadata and available fields which you can use in the processing functions. Check the frictionlessdata docs for more details about the datapackage file format. Main processing functions End of explanation """ Flow(*load_steps, *process_steps, dump_to_path('data/committee-meeting-attendees-parts')).process() """ Explanation: Run the flow End of explanation """ from collections import deque top_attended_member_names = [member_names[mk_id] for mk_id, num_attended in deque(sorted(member_attended_meetings.items(), key=lambda kv: kv[1]), maxlen=5)] print('\n') print('-- top attended members --') print(top_attended_member_names) print('\n') print('-- stats --') print(yaml.dump(dict(stats), default_flow_style=False, allow_unicode=True)) """ Explanation: Aggregate and print stats End of explanation """
quantopian/research_public
notebooks/lectures/Position_Concentration_Risk/answers/notebook.ipynb
apache-2.0
import numpy as np import pandas as pd import scipy.stats as stats import matplotlib.pyplot as plt import math import cvxpy """ Explanation: Exercise Answer Key: Position Concentration Risk Lecture Link This exercise notebook refers to this lecture. Please use the lecture for explanations and sample code. https://www.quantopian.com/lectures#Position-Concentration-Risk Part of the Quantopian Lecture Series: www.quantopian.com/lectures github.com/quantopian/research_public End of explanation """ def get_markowitz_weights(mu, Sigma, gamma=1, max_position=1.0, max_leverage=1.0, short=False): w = cvxpy.Variable(len(Sigma)) g = cvxpy.Parameter(sign='positive') L = cvxpy.Parameter() g.value = gamma L.value = max_leverage try: ret = mu.T*w except ValueError: ret = mu*w risk = cvxpy.quad_form(w, Sigma) objective = cvxpy.Maximize(ret - g*risk) constraints = [ cvxpy.abs(w) < max_position, cvxpy.norm(w, 1) <= L, # Make it so we don't have to invest everything ] if not short: constraints.append(w >= 0) # Force all positive weights prob = cvxpy.Problem( objective, constraints ) result = prob.solve() return w.value """ Explanation: Helper Functions End of explanation """ universes = 1000 evens = 19 total = 38 payout = 100 rounds = 1 results = np.zeros(universes) #Your code goes here p = float(19)/total for i in range(universes): results[i] = payout * np.random.binomial(n = rounds, p = p) print "Payout mean:", np.mean(results) print "Payout std:", np.std(results) """ Explanation: Exercise 1: Roulette Simulation A roulette table has 38 pockets: 1 through 36, 0, and 00. A bet on an even number pays out at a ratio of 1:1. Landing on 0 and 00 count as losing. You have $100 and are betting on an even number. a. All In By running 1000 simulations, find the mean and standard deviation of the payout if you bet your entire $100 on one round. End of explanation """ universes = 1000 evens = 19 total = 38 payout = 1 rounds = 100 results = np.zeros(universes) #Your code goes here p = float(19)/total for i in range(universes): results[i] = payout * np.random.binomial(n = rounds, p = p) print "Payout mean:", np.mean(results) print "Payout std:", np.std(results) """ Explanation: b. $1 Bets By running 1000 simulations, find the mean and standard deviation of the payout if instead you bet $1 at a time and play 100 rounds. End of explanation """ time_start = '2015-01-01' time_halfway = '2015-07-01' time_end = '2016-01-01' AMZN_r = get_pricing('AMZN', fields='price', start_date=time_start, end_date=time_end).pct_change()[1:] X = np.linspace(0, len(AMZN_r), len(AMZN_r)) #Your code goes here print "AMZN returns std:", np.std(AMZN_r.loc[time_halfway:]) AMZN_r.plot(alpha = 0.5); plt.legend(); """ Explanation: Exercise 2: Portfolio Diversification a. Single Asset Use the pricing data below to find the standard deviation of the returns of AMZN in the second half of the year 2015 and plot the price against time. End of explanation """ symbol_list = ['BEN', 'SYMC', 'IP', 'SWKS', 'IVZ', 'MJN', 'WMB', 'LB', 'TWX', 'NFX', 'PFE', 'LLY', 'HP', 'JPM', 'CXO', 'TJX', 'CAG', 'BBT', 'ATVI', 'NFLX'] prices_df = get_pricing(symbol_list, fields=['price'] , start_date=time_start, end_date=time_end)['price'] prices_df.columns = map(lambda x: x.symbol, prices_df.columns) eweights_df = len(symbol_list) * [float(1)/len(symbol_list)] returns_df = prices_df.pct_change(1)[1:] #Your code goes here returns_df['EWP'] = returns_df[symbol_list].dot(eweights_df) print "AMZN returns std:", np.std(AMZN_r.loc[time_halfway:]) print "Portfolio returns std:", np.std(returns_df['EWP'].loc[time_halfway:]) AMZN_r.plot(alpha = 0.5); returns_df['EWP'].loc[time_halfway:].plot(); plt.legend(); """ Explanation: b. Equally Weighted Portfolio Create an equally weighted portfolio of the following 10 stocks, find the standard deviation of the portfolio's returns, and then plot the returns for the second half of 2015 along with the AMZN returns from above. Putting AMZN in a portfolio of 19 other securities should diversify the idiosyncratic risk and lower the price variability. Hint: To calculate weighted returns dot the weight matrix eweights_df with the splice of the returns matrix containing the symbol_list pricing data (returns_df[symbol_list]). End of explanation """ #Pipeline Setup from quantopian.research import run_pipeline from quantopian.pipeline import Pipeline from quantopian.pipeline.data import morningstar from quantopian.pipeline.factors import CustomFactor from quantopian.pipeline.classifiers.morningstar import Sector from quantopian.pipeline.filters import QTradableStocksUS from time import time universe = QTradableStocksUS() pipe = Pipeline(columns = {'Market Cap' : morningstar.valuation.market_cap.latest}, screen=universe ) start_timer = time() results = run_pipeline(pipe, time_start, time_end) end_timer = time() results.fillna(value=0); print "Time to run pipeline %.2f secs" % (end_timer - start_timer) # This is important as sometimes the first data returned won't be on the specified start date first_trading_day = results.index.levels[0][1] market_cap = results.loc[first_trading_day]['Market Cap'] market_cap.index = [x.symbol for x in market_cap.index]#pd.MultiIndex.from_tuples([(x[0], x[1].symbol) for x in market_cap.index]) mcs = market_cap # pd.DataFrame(market_cap.loc[(first_trading_day,)].loc[symbol_list]).transpose() mweights = (mcs[symbol_list]/sum(mcs[symbol_list])).transpose() #Your code goes here returns_df['MWP'] = returns_df[symbol_list].dot(mweights) print "AMZN returns std:", np.std(AMZN_r.loc[time_halfway:]) print "EWP returns std:", np.std(returns_df['EWP'].loc[time_halfway:]) print "MWP returns std:", np.std(returns_df['MWP'].loc[time_halfway:]) AMZN_r[time_halfway:].plot(alpha = 0.5); returns_df['EWP'].loc[time_halfway:].plot(alpha = 0.5); returns_df['MWP'].loc[time_halfway:].plot(); plt.legend(); """ Explanation: c. Market Weighted Portfolio Create a new portfolio of the same assets, this time weighted by market capitalization, find the standard deviation of the portfolio returns, and then plot the portfolio returns along with both results from above. Weighting using market capitalization brings us closer to the theoretical efficient portfolio, a portfolio of investments containing every single asset on the market, each weighted proportionately to its presence in the market. The market cap is found using a pipeline factor, the steps for which are below. End of explanation """ mu = returns_df[symbol_list].\ loc[:time_halfway].fillna(0).mean().as_matrix() sigma = returns_df[symbol_list].\ loc[:time_halfway].fillna(0).cov().as_matrix() mkweights_df = get_markowitz_weights(mu, sigma) #Your code goes here returns_df['MKW'] = returns_df[symbol_list].dot(mkweights_df) print "AMZN returns std:", np.std(AMZN_r.loc[time_halfway:]) print "EWP returns std:", np.std(returns_df['EWP'].loc[time_halfway:]) print "MWP returns std:", np.std(returns_df['MWP'].loc[time_halfway:]) print "MKW returns std:", np.std(returns_df['MKW'].loc[time_halfway:]), "\n" AMZN_r.loc[time_halfway:].plot(alpha = 0.5); returns_df['EWP'].loc[time_halfway:].plot(alpha = 0.5); returns_df['MWP'].loc[time_halfway:].plot(alpha = 0.5); returns_df['MKW'].loc[time_halfway:].plot(); plt.legend(); """ Explanation: d. Markowitz Portfolio Create a new portfolio of the same assets, this time using the get_markowitz_weights helper function to create the Markowitz mean-variance portfolio. Use the pricing data from the first half of 2015 to calibrate the weights, and then plot the portfolio returns for the second half of 2015. Important Note If the weights from the lookback window (6 prior months), are correlated with the weights of the forward window (6 following months), then this optimization should be helpful in reducing out portfolio volatility going forward. However, this is often not the case in real life. Real markets are complicated, and historical volatility may not be a good predictor of future volatility. Volatility forecasting models are an entire area of research in finance, so don't think that just because historic volatility of your portfolio was low, it will be equally low in the future. This is just one technique that attempts to control portfolio risk, there is a more complete discussion of this in this lecture: https://www.quantopian.com/lectures/risk-constrained-portfolio-optimization End of explanation """
cgivre/oreilly-sec-ds-fundamentals
Notebooks/Unsupervised/K-Means Clustering Example.ipynb
apache-2.0
data = pd.DataFrame([[1, 2], [5, 8], [1.5, 1.8], [8, 8], [1, 0.6], [9, 11]], columns=['x','y']) print( data ) """ Explanation: K-Means Clustering Example In this example notebook, you will see how to implement K-Means Clustering in Python using Scikit-Learn and Pandas. Adapted from https://pythonprogramming.net/flat-clustering-machine-learning-python-scikit-learn/ Step 1: Get Data: The first step is to prepare or generate the data. In this dataset, the observations only have two features, but K-Means can be used with any number of features. Since this is an unsupervised example, it is not necessary to have a "target" column. End of explanation """ kmeans = KMeans(n_clusters=2).fit(data) centroids = kmeans.cluster_centers_ labels = kmeans.labels_ print(centroids) print(labels) """ Explanation: Step 2: Build the Model: Much like the supervised models, you first create the model then call the .fit() method using your data source. The model is now populated with both your centroids and labels. These can be accessed via the .cluster_centers_ and labels_ properties respectively. You can view the complete documentation here: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html K-Means also has a .predict() method which can be used to predict the label for an observation. End of explanation """ data['labels'] = labels #plt.plot(data, colors[data['labels'], markersize = 10) group1 = data[data['labels']==1].plot( kind='scatter', x='x', y='y', color='DarkGreen', label="Group 1" ) group2 = data[data['labels']==0].plot( kind='scatter', x='x', y='y', color='Brown', ax=group1, label="Group 2" ) group1.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=3, fancybox=True, shadow=True) plt.scatter(centroids[:, 0],centroids[:, 1], marker = "x", s=150, linewidths = 5, zorder = 10) plt.show() """ Explanation: Visualizing the Clusters The code below visualizes the clusters. End of explanation """
materialsvirtuallab/nano106
lectures/lecture_4_point_group_symmetry/Symmetry Computations on mmm (D_2h) Point Group.ipynb
bsd-3-clause
import numpy as np import itertools from sympy import symbols """ Explanation: NANO106 - Symmetry Computations on $mmm (D_{2h})$ Point Group by Shyue Ping Ong This notebook demonstrates the computation of orbits in the mmm point group. It is part of course material for UCSD's NANO106 - Crystallography of Materials. Unlike the $m\overline{3}m (O_h)$ version, this duplicates relevant code from the symmetry package to explicitly demonstrate the priniciples of generating point group symmetry operations. Preliminaries Let's start by importing the numpy, sympy and other packages we need. End of explanation """ def in_array_list(array_list, a): for i in array_list: if np.all(np.equal(a, i)): return True return False """ Explanation: We will now define a useful function for checking existence of np.arrays in a list of arrays. It is not the most efficient implementation, but would suffice for our purposes. End of explanation """ generators = [] for i in xrange(3): g = np.eye(3).astype(np.int) g[i, i] = -1 generators.append(g) """ Explanation: Generating the Symmetry Operations Next, we specify the generators for mmm point group, which are the three mirror planes. Note that the existence of the three two-fold rotation axes is implied by the existence of the three mirror planes. End of explanation """ symm_ops = [] symm_ops.extend(generators) new_ops = generators while len(new_ops) > 0: gen_ops = [] for g1, g2 in itertools.product(new_ops, symm_ops): #Note that we cast the op to int to improve presentation of the results. #This is fine in crystallographic reference frame. op = np.dot(g1, g2) if not in_array_list(symm_ops, op): gen_ops.append(op) symm_ops.append(op) op = np.dot(g2, g1) if not in_array_list(symm_ops, op): gen_ops.append(op) symm_ops.append(op) new_ops = gen_ops print "The order of the group is %d. The group matrices are:" % len(symm_ops) for op in symm_ops: print op """ Explanation: We will now generate all the group symmetry operation matrices from the generators. End of explanation """ x, y, z = symbols("x y z") def get_orbit(symm_ops, p): """Given a set of symmops and a point p, this function returns the orbit""" orbit = [] for o in symm_ops: pp = np.dot(o, p) if not in_array_list(orbit, pp): orbit.append(pp) return orbit """ Explanation: Computing Orbits Using sympy, we specify the symbolic symbols x, y, z to represent position coordinates. We also define a function to generate the orbit given a set of symmetry operations and a point p. End of explanation """ p = np.array([x, y, z]) print "For the general position %s, the orbit is " % str(p) for o in get_orbit(symm_ops, p): print o, """ Explanation: Orbit for General Position End of explanation """ p = np.array([0, 0, z]) orb = get_orbit(symm_ops, p) print "For the special position %s on the two-fold axis, the orbit comprise %d points:" % (str(p), len(orb)) for o in orb: print o, """ Explanation: Orbit for Special Position on two-fold rotation axes End of explanation """ p = np.array([x, y, 0]) orb = get_orbit(symm_ops, p) print "For the special position %s on the two-fold axis, the orbit comprise %d points:" % (str(p), len(orb)) for o in orb: print o, """ Explanation: The orbit is similar for the other two-fold axes on the a and b axes are similar. Orbit for Special Position on mirror planes Positions on the mirror on the a-b plane have coordinates (x, y, 0). End of explanation """
jbwhit/jupyter-best-practices
notebooks/07-Some_basics.ipynb
mit
# Create a [list] days = ['Monday', # multiple lines 'Tuesday', # acceptable 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', # trailing comma is fine! ] days # Simple for-loop for day in days: print(day) # Double for-loop for day in days: for letter in day: print(letter) print(days) print(*days) # Double for-loop for day in days: for letter in day: print(letter) print() for day in days: for letter in day: print(letter.lower()) """ Explanation: Github https://github.com/jbwhit/OSCON-2015/commit/6750b962606db27f69162b802b5de4f84ac916d5 A few Python Basics End of explanation """ length_of_days = [len(day) for day in days] length_of_days letters = [letter for day in days for letter in day] print(letters) letters = [letter for day in days for letter in day] print(letters) [num for num in xrange(10) if num % 2] [num for num in xrange(10) if num % 2 else "doesn't work"] [num if num % 2 else "works" for num in xrange(10)] [num for num in xrange(10)] sorted_letters = sorted([x.lower() for x in letters]) print(sorted_letters) unique_sorted_letters = sorted(set(sorted_letters)) print("There are", len(unique_sorted_letters), "unique letters in the days of the week.") print("They are:", ''.join(unique_sorted_letters)) print("They are:", '; '.join(unique_sorted_letters)) def first_three(input_string): """Takes an input string and returns the first 3 characters.""" return input_string[:3] import numpy as np # tab np.linspace() [first_three(day) for day in days] def last_N(input_string, number=2): """Takes an input string and returns the last N characters.""" return input_string[-number:] [last_N(day, 4) for day in days if len(day) > 6] from math import pi print([str(round(pi, i)) for i in xrange(2, 9)]) list_of_lists = [[i, round(pi, i)] for i in xrange(2, 9)] print(list_of_lists) for sublist in list_of_lists: print(sublist) # Let this be a warning to you! # If you see python code like the following in your work: for x in range(len(list_of_lists)): print("Decimals:", list_of_lists[x][0], "expression:", list_of_lists[x][1]) print(list_of_lists) # Change it to look more like this: for decimal, rounded_pi in list_of_lists: print("Decimals:", decimal, "expression:", rounded_pi) # enumerate if you really need the index for index, day in enumerate(days): print(index, day) """ Explanation: List Comprehensions End of explanation """ from IPython.display import IFrame, HTML HTML('<iframe src=https://en.wikipedia.org/wiki/Hash_table width=100% height=550></iframe>') fellows = ["Jonathan", "Alice", "Bob"] universities = ["UCSD", "UCSD", "Vanderbilt"] for x, y in zip(fellows, universities): print(x, y) # Don't do this {x: y for x, y in zip(fellows, universities)} # Doesn't work like you might expect {zip(fellows, universities)} dict(zip(fellows, universities)) fellows fellow_dict = {fellow.lower(): university for fellow, university in zip(fellows, universities)} fellow_dict fellow_dict['bob'] rounded_pi = {i:round(pi, i) for i in xrange(2, 9)} rounded_pi[5] sum([i ** 2 for i in range(10)]) sum(i ** 2 for i in range(10)) huh = (i ** 2 for i in range(10)) huh.next() """ Explanation: Dictionaries Python dictionaries are awesome. They are hash tables and have a lot of neat CS properties. Learn and use them well. End of explanation """
takanory/python-machine-learning
10 Minutes to pandas.ipynb
mit
# それぞれ必要なものを import するけど、こういう風に短く書くのがこっち界隈だと一般的らしい import pandas as pd import numpy as np import matplotlib.pyplot as plt """ Explanation: 10 Minutes to pandas写経 https://pandas.pydata.org/pandas-docs/stable/10min.html をやってみる End of explanation """ # Creating a Series by passing a list of values, letting pandas create a default integer index: # リストを指定してシリーズを作成すると、Pandasはデフォルトで数値のインデックスを生成する s = pd.Series([1,3,5,np.nan,6,8]) s # まずは日付のインデックスを作成 dates = pd.date_range('20130101', periods=6) dates # Creating a DataFrame by passing a numpy array, with a datetime index and labeled columns: # numpy arrayを渡してDataFrameを作成する時に、インデックスと列名を指定 df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) df # Creating a DataFrame by passing a dict of objects that can be converted to series-like. # DataFrame作成時に辞書を渡すと、それぞれの辞書の値を Series のように扱う df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 'D' : np.array([3] * 4,dtype='int32'), 'E' : pd.Categorical(["test","train","test","train"]), 'F' : 'foo' }) df2 # Having specific dtypes # それぞれ特定のデータ型(dtypes)を持つ df2.dtypes # If you’re using IPython, tab completion for column names (as well as public attributes) is automatically enabled. # Here’s a subset of the attributes that will be completed: # IPython使っていたら db2. で TAB を入力すると列名が自動的に補完対象になる # Jupyter notebok だと TAB を入力すると補完するための一覧がリストボックスで表示される """ Explanation: Object creation Intro to Data Structures — pandas 0.20.1 documentation Series と DataFrame を作る練習 End of explanation """ # See the top & bottom rows of the frame # DataFrame の先頭と最後の行を参照する df.head() df.tail(3) # Display the index, columns, and the underlying numpy data # インデックス、列、値を参照する print(df.index) print(df.columns) print(df.values) # Describe shows a quick statistic summary of your data # データの特徴(平均、中央値、最大、最小など)を表示する df.describe() # Transposing your data # データを転置する(インデックスと列を入れ替える) df.T # Sorting by an axis # インデックスでソートする(axis=1なので横方向) df.sort_index(axis=1, ascending=False) # Sorting by values # 値でソートする(ここではB列を指定している) df.sort_values(by='B') """ Explanation: Viewing Data Essential Basic Functionality — pandas 0.20.1 documentation データを参照する練習 End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/bcc/cmip6/models/sandbox-2/atmoschem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'bcc', 'sandbox-2', 'atmoschem') """ Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: BCC Source ID: SANDBOX-2 Topic: Atmoschem Sub-Topics: Transport, Emissions Concentrations, Gas Phase Chemistry, Stratospheric Heterogeneous Chemistry, Tropospheric Heterogeneous Chemistry, Photo Chemistry. Properties: 84 (39 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:39 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Key Properties --&gt; Timestep Framework 4. Key Properties --&gt; Timestep Framework --&gt; Split Operator Order 5. Key Properties --&gt; Tuning Applied 6. Grid 7. Grid --&gt; Resolution 8. Transport 9. Emissions Concentrations 10. Emissions Concentrations --&gt; Surface Emissions 11. Emissions Concentrations --&gt; Atmospheric Emissions 12. Emissions Concentrations --&gt; Concentrations 13. Gas Phase Chemistry 14. Stratospheric Heterogeneous Chemistry 15. Tropospheric Heterogeneous Chemistry 16. Photo Chemistry 17. Photo Chemistry --&gt; Photolysis 1. Key Properties Key properties of the atmospheric chemistry 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmospheric chemistry model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of atmospheric chemistry model code. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.chemistry_scheme_scope') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "troposhere" # "stratosphere" # "mesosphere" # "mesosphere" # "whole atmosphere" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Chemistry Scheme Scope Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Atmospheric domains covered by the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.basic_approximations') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basic approximations made in the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.prognostic_variables_form') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "3D mass/mixing ratio for gas" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.5. Prognostic Variables Form Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Form of prognostic variables in the atmospheric chemistry component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.number_of_tracers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 1.6. Number Of Tracers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of advected tracers in the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.family_approach') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.7. Family Approach Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry calculations (not advection) generalized into families of species? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.coupling_with_chemical_reactivity') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.8. Coupling With Chemical Reactivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry transport scheme turbulence is couple with chemical reactivity? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Software Properties Software properties of aerosol code 2.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Operator splitting" # "Integrated" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestep Framework Timestepping in the atmospheric chemistry model 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Mathematical method deployed to solve the evolution of a given variable End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_advection_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.2. Split Operator Advection Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemical species advection (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_physical_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.3. Split Operator Physical Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for physics (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_chemistry_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.4. Split Operator Chemistry Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemistry (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_alternate_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3.5. Split Operator Alternate Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.6. Integrated Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the atmospheric chemistry model (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Explicit" # "Implicit" # "Semi-implicit" # "Semi-analytic" # "Impact solver" # "Back Euler" # "Newton Raphson" # "Rosenbrock" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3.7. Integrated Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the type of timestep scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.turbulence') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Timestep Framework --&gt; Split Operator Order ** 4.1. Turbulence Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for turbulence scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.convection') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.2. Convection Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for convection scheme This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.precipitation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.3. Precipitation Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for precipitation scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.emissions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.4. Emissions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for emissions scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.5. Deposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for deposition scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.gas_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.6. Gas Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for gas phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.tropospheric_heterogeneous_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.7. Tropospheric Heterogeneous Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for tropospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.stratospheric_heterogeneous_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.8. Stratospheric Heterogeneous Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for stratospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.photo_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.9. Photo Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for photo chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.aerosols') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.10. Aerosols Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for aerosols scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Tuning Applied Tuning methodology for atmospheric chemistry component 5.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview description of tuning: explain and motivate the main targets and metrics retained. &amp;Document the relative weight given to climate performance metrics versus process oriented metrics, &amp;and on the possible conflicts with parameterization level tuning. In particular describe any struggle &amp;with a parameter value that required pushing it to its limits to solve a particular model deficiency. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics of the global mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics of mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Grid Atmospheric chemistry grid 6.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the atmopsheric chemistry grid End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.matches_atmosphere_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.2. Matches Atmosphere Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 * Does the atmospheric chemistry grid match the atmosphere grid?* End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Grid --&gt; Resolution Resolution in the atmospheric chemistry grid 7.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Canonical Horizontal Resolution Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.number_of_horizontal_gridpoints') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.3. Number Of Horizontal Gridpoints Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Total number of horizontal (XY) points (or degrees of freedom) on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.4. Number Of Vertical Levels Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Number of vertical levels resolved on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.is_adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 7.5. Is Adaptive Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Default is False. Set true if grid resolution changes during execution. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Transport Atmospheric chemistry transport 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview of transport implementation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.use_atmospheric_transport') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 8.2. Use Atmospheric Transport Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is transport handled by the atmosphere, rather than within atmospheric cehmistry? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.transport_details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.3. Transport Details Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If transport is handled within the atmospheric chemistry scheme, describe it. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Emissions Concentrations Atmospheric chemistry emissions 9.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview atmospheric chemistry emissions End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Vegetation" # "Soil" # "Sea surface" # "Anthropogenic" # "Biomass burning" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10. Emissions Concentrations --&gt; Surface Emissions ** 10.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of the chemical species emitted at the surface that are taken into account in the emissions scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Climatology" # "Spatially uniform mixing ratio" # "Spatially uniform concentration" # "Interactive" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.2. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Methods used to define chemical species emitted directly into model layers above the surface (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed via a climatology, and the nature of the climatology (E.g. CO (monthly), C2H6 (constant)) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.4. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.6. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via any other method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Aircraft" # "Biomass burning" # "Lightning" # "Volcanos" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11. Emissions Concentrations --&gt; Atmospheric Emissions TO DO 11.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of chemical species emitted in the atmosphere that are taken into account in the emissions scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Climatology" # "Spatially uniform mixing ratio" # "Spatially uniform concentration" # "Interactive" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Methods used to define the chemical species emitted in the atmosphere (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed via a climatology (E.g. CO (monthly), C2H6 (constant)) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.4. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.6. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and specified via an &quot;other method&quot; End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_lower_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12. Emissions Concentrations --&gt; Concentrations TO DO 12.1. Prescribed Lower Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the lower boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_upper_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.2. Prescribed Upper Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the upper boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 13. Gas Phase Chemistry Atmospheric chemistry transport 13.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview gas phase atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HOx" # "NOy" # "Ox" # "Cly" # "HSOx" # "Bry" # "VOCs" # "isoprene" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Species included in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_bimolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.3. Number Of Bimolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of bi-molecular reactions in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_termolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.4. Number Of Termolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of ter-molecular reactions in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_tropospheric_heterogenous_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.5. Number Of Tropospheric Heterogenous Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_stratospheric_heterogenous_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.6. Number Of Stratospheric Heterogenous Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_advected_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.7. Number Of Advected Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of advected species in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.8. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of gas phase species for which the concentration is updated in the chemical solver assuming photochemical steady state End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.interactive_dry_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.9. Interactive Dry Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.10. Wet Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet deposition included? Wet deposition describes the moist processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_oxidation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.11. Wet Oxidation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet oxidation included? Oxidation describes the loss of electrons or an increase in oxidation state by a molecule End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14. Stratospheric Heterogeneous Chemistry Atmospheric chemistry startospheric heterogeneous chemistry 14.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview stratospheric heterogenous atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Cly" # "Bry" # "NOy" # TODO - please enter value(s) """ Explanation: 14.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Gas phase species included in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Polar stratospheric ice" # "NAT (Nitric acid trihydrate)" # "NAD (Nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particule))" # TODO - please enter value(s) """ Explanation: 14.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.sedimentation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.5. Sedimentation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sedimentation is included in the stratospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the stratospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Tropospheric Heterogeneous Chemistry Atmospheric chemistry tropospheric heterogeneous chemistry 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview tropospheric heterogenous atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of gas phase species included in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Nitrate" # "Sea salt" # "Dust" # "Ice" # "Organic" # "Black carbon/soot" # "Polar stratospheric ice" # "Secondary organic aerosols" # "Particulate organic matter" # TODO - please enter value(s) """ Explanation: 15.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.interactive_dry_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.5. Interactive Dry Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the tropospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 16. Photo Chemistry Atmospheric chemistry photo chemistry 16.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview atmospheric photo chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.number_of_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 16.2. Number Of Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the photo-chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline (clear sky)" # "Offline (with clouds)" # "Online" # TODO - please enter value(s) """ Explanation: 17. Photo Chemistry --&gt; Photolysis Photolysis scheme 17.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Photolysis scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.environmental_conditions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.2. Environmental Conditions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any environmental conditions taken into account by the photolysis scheme (e.g. whether pressure- and temperature-sensitive cross-sections and quantum yields in the photolysis calculations are modified to reflect the modelled conditions.) End of explanation """
cloudmesh/book
notebooks/scipy/scipy-examples.ipynb
apache-2.0
import numpy as np # import numpy import scipy as sp # import scipy from scipy import stats # refer directly to stats rather than sp.stats import matplotlib as mpl # for visualization from matplotlib import pyplot as plt # refer directly to pyplot # rather than mpl.pyplot # for exporting PDF's we need to import PdfPages from matplotlib.backends.backend_pdf import PdfPages """ Explanation: Scipy Examples First we add the usual scientific computing modules with the typical abbreviations, including sp for scipy. We could invoke scipy's statistical package as sp.stats, but for the sake of laziness we abbreviate that too. End of explanation """ s = sp.randn(100) """ Explanation: Now we create some random data to play with. We generate 100 samples from a Gaussian distribution centered at zero. End of explanation """ print ('There are',len(s),'elements in the set') """ Explanation: How many elements are in the set? End of explanation """ print ('The mean of the set is',s.mean()) """ Explanation: What is the mean (average) of the set? End of explanation """ print ('The minimum of the set is',s.min()) """ Explanation: What is the minimum of the set? End of explanation """ print ('The maximum of the set is',s.max()) """ Explanation: What is the maximum of the set? End of explanation """ print ('The median of the set is',sp.median(s)) """ Explanation: We can use the scipy functions too. What's the median? End of explanation """ print ('The standard deviation is',sp.std(s), 'and the variance is',sp.var(s)) """ Explanation: What about the standard deviation and variance? End of explanation """ print ('The square of the standard deviation is',sp.std(s)**2) """ Explanation: Isn't the variance the square of the standard deviation? End of explanation """ print ('The difference is',abs(sp.std(s)**2 - sp.var(s))) print ('And in decimal form, the difference is %0.16f' % (abs(sp.std(s)**2 - sp.var(s)))) """ Explanation: How close are the measures? The differences are close as the following calculation shows End of explanation """ plt.hist(s) # yes, one line of code for a histogram plt.show() """ Explanation: How does this look as a histogram? End of explanation """ plt.clf() # clear out the previous plot plt.hist(s) plt.title("Histogram Example") plt.xlabel("Value") plt.ylabel("Frequency") plt.show() """ Explanation: Let's add some titles. End of explanation """ plt.clf() # clear out the previous plot plt.hist(s) plt.xlabel("Value") plt.ylabel("Frequency") plt.show() """ Explanation: Typically we do not include titles when we prepare images for inclusion in LaTeX. There we use the caption to describe what the figure is about. End of explanation """ import random def F(x): return 2*x - 2 def add_noise(x): return x + random.uniform(-1,1) X = range(0,10,1) Y = [] for i in range(len(X)): Y.append(add_noise(X[i])) plt.clf() # clear out the old figure plt.plot(X,Y,'.') plt.show() """ Explanation: Let's try out some linear regression, or curve fitting. End of explanation """ m, b, r, p, est_std_err = stats.linregress(X,Y) """ Explanation: Now let's try linear regression to fit the curve. End of explanation """ print ('The slope is',m,'and the y-intercept is', b) def Fprime(x): # the fitted curve return m*x + b """ Explanation: What is the slope and y-intercept of the fitted curve? End of explanation """ X = range(0,10,1) Yprime = [] for i in range(len(X)): Yprime.append(Fprime(X[i])) plt.clf() # clear out the old figure # the observed points, blue dots plt.plot(X, Y, '.', label='observed points') # the interpolated curve, connected red line plt.plot(X, Yprime, 'r-', label='estimated points') plt.title("Linear Regression Example") # title plt.xlabel("x") # horizontal axis title plt.ylabel("y") # vertical axis title # legend labels to plot plt.legend(['obsered points', 'estimated points']) """ Explanation: Now let's see how well the curve fits the data. We'll call the fitted curve F'. End of explanation """ plt.savefig("regression.pdf", bbox_inches='tight') """ Explanation: To save the figure for inclusion in LaTeX as PDF End of explanation """ plt.savefig('regression.png') plt.show() """ Explanation: To save it as png you can use the following, but you need to use the PDF format if you like to include it in a document. End of explanation """
AntArch/Presentations_Github
20151008_OpenGeo_Reuse_under_licence/20151008_OpenGeo_Reuse_under_licence.ipynb
cc0-1.0
from IPython.display import YouTubeVideo YouTubeVideo('F4rFuIb1Ie4') ## PDF output using pandoc import os ### Export this notebook as markdown commandLineSyntax = 'ipython nbconvert --to markdown 20151008_OpenGeo_Reuse_under_licence.ipynb' print (commandLineSyntax) os.system(commandLineSyntax) ### Export this notebook and the document header as PDF using Pandoc commandLineSyntax = 'pandoc -f markdown -t latex -N -V geometry:margin=1in DocumentHeader.md 20151008_OpenGeo_Reuse_under_licence.md --filter pandoc-citeproc --latex-engine=xelatex --toc -o interim.pdf ' os.system(commandLineSyntax) ### Remove cruft from the pdf commandLineSyntax = 'pdftk interim.pdf cat 1-3 16-end output 20151008_OpenGeo_Reuse_under_licence.pdf' os.system(commandLineSyntax) ### Remove the interim pdf commandLineSyntax = 'rm interim.pdf' os.system(commandLineSyntax) """ Explanation: Go down for licence and other metadata about this presentation \newpage Preamble Licence Unless stated otherwise all content is released under a [CC0]+BY licence. I'd appreciate it if you reference this but it is not necessary. \newpage Using Ipython for presentations A short video showing how to use Ipython for presentations End of explanation """ %install_ext https://raw.githubusercontent.com/rasbt/python_reference/master/ipython_magic/watermark.py %load_ext watermark %watermark -a "Anthony Beck" -d -v -m -g #List of installed conda packages !conda list #List of installed pip packages !pip list """ Explanation: The environment In order to replicate my environment you need to know what I have installed! Set up watermark This describes the versions of software used during the creation. Please note that critical libraries can also be watermarked as follows: python %watermark -v -m -p numpy,scipy End of explanation """ !ipython nbconvert 20151008_OpenGeo_Reuse_under_licence.ipynb --to slides --post serve """ Explanation: Running dynamic presentations You need to install the RISE Ipython Library from Damián Avila for dynamic presentations To convert and run this as a static presentation run the following command: End of explanation """ #Future proof python 2 from __future__ import print_function #For python3 print syntax from __future__ import division # def import IPython.core.display # A function to collect user input - ipynb_input(varname='username', prompt='What is your username') def ipynb_input(varname, prompt=''): """Prompt user for input and assign string val to given variable name.""" js_code = (""" var value = prompt("{prompt}",""); var py_code = "{varname} = '" + value + "'"; IPython.notebook.kernel.execute(py_code); """).format(prompt=prompt, varname=varname) return IPython.core.display.Javascript(js_code) # inline %pylab inline """ Explanation: To close this instances press control 'c' in the ipython notebook terminal console Static presentations allow the presenter to see speakers notes (use the 's' key) If running dynamically run the scripts below Pre load some useful libraries End of explanation """ from IPython.display import YouTubeVideo YouTubeVideo('jUzGF401vLc') """ Explanation: \newpage About me Research Fellow, University of Nottingham: orcid Director, Geolytics Limited - A spatial data analytics consultancy About this presentation Available on GitHub - https://github.com/AntArch/Presentations_Github/ Fully referenced PDF \newpage A potted history of mapping In the beginning was the geoword and the word was cartography \newpage Cartography was king. Static representations of spatial knowledge with the cartographer deciding what to represent. \newpage And then there was data ......... \newpage Restrictive data \newpage Making data interoperable and open \newpage Technical interoperability - levelling the field \newpage Facilitating data driven visualization From Map to Model The changing paradigm of map creation from cartography to data driven visualization \newpage \newpage \newpage \newpage So where are these new data products? \newpage Non-technical interoperability issues? Issues surrounding non-technical interoperability include: Policy interoperabilty Licence interoperability Legal interoperability Social interoperability We will focus on licence interoperability \newpage There is a multitude of formal and informal data. \newpage What is a licence? Wikipedia state: A license may be granted by a party ("licensor") to another party ("licensee") as an element of an agreement between those parties. A shorthand definition of a license is "an authorization (by the licensor) to use the licensed material (by the licensee)." Each of these data objects can be licenced in a different way. This shows some of the licences described by the RDFLicence ontology \newpage Concepts (derived from Formal Concept Analysis) surrounding licences \newpage Two lead organisations have developed legal frameworks for content licensing: Creative Commons (CC) and Open Data Commons (ODC). Until the release of CC version 4, published in November 2013, the CC licence did not cover data. Between them, CC and ODC licences can cover all forms of digital work. There are many other licence types Many are bespoke Bespoke licences are difficult to manage Many legacy datasets have bespoke licences I'll describe CC in more detail \newpage Creative Commons Zero Creative Commons Zero (CC0) is essentially public domain which allows: Reproduction Distribution Derivations Constraints on CC0 The following clauses constrain CC0: Permissions ND – No derivatives: the licensee can not derive new content from the resource. Requirements BY – By attribution: the licensee must attribute the source. SA – Share-alike: if the licensee adapts the resource, it must be released under the same licence. Prohibitions NC – Non commercial: the licensee must not use the work commercially without prior approval. CC license combinations License|Reproduction|Distribution|Derivation|ND|BY|SA|NC ----|----|----|----|----|----|----|---- CC0|X|X|X|||| CC-BY-ND|X|X||X|X|| CC-BY-NC-ND|X|X||X|X||X CC-BY|X|X|X||X|| CC-BY-SA|X|X|X||X|X| CC-BY-NC|X|X|X||X||X CC-BY-NC-SA|X|X|X||X|X|X Table: Creative Commons license combinations \newpage Why are licenses important? They tell you what you can and can't do with 'stuff' Very significant when multiple datasets are combined It then becomes an issue of license compatibility \newpage Which is important when we mash up data Certain licences when combined: Are incompatible Creating data islands Inhibit commercial exploitation (NC) Force the adoption of certain licences If you want people to commercially exploit your stuff don't incorporate CC-BY-NC-SA data! Stops the derivation of new works A conceptual licence processing workflow. The licence processing service analyses the incoming licence metadata and determines if the data can be legally integrated and any resulting licence implications for the derived product. \newpage A rudimentry logic example ``` Data1 hasDerivedContentIn NewThing. Data1 hasLicence a cc-by-sa. What hasLicence a cc-by-sa? #reason here If X hasDerivedContentIn Y and hasLicence Z then Y hasLicence Z. #reason here Data2 hasDerivedContentIn NewThing. Data2 hasLicence a cc-by-nc-sa. What hasLicence a cc-by-nc-sa? #reason here Nothing hasLicence a cc-by-nc-sa and hasLicence a cc-by-sa. #reason here ``` And processing this within the Protege reasoning environment End of explanation """ from IPython.display import YouTubeVideo YouTubeVideo('tkRB5Rp1_W4') """ Explanation: \newpage Here's something I prepared earlier A live presentation (for those who weren't at the event)..... End of explanation """
tpin3694/tpin3694.github.io
mathematics/argmin_and_argmax.ipynb
mit
import numpy as np import pandas as pd np.random.seed(1) """ Explanation: Title: argmin and argmax Slug: argmin_and_argmax Summary: An explanation of argmin and argmax in Python. Date: 2016-01-23 12:00 Category: Mathematics Tags: Basics Authors: Chris Albon argmin and argmax are the inputs, x's, to a function, f, that creates the smallest and largest outputs, f(x). Preliminaries End of explanation """ # Define a function that, def f(x): # Outputs x multiplied by a random number drawn from a normal distribution return x * np.random.normal(size=1)[0] """ Explanation: Define A Function, f(x) End of explanation """ # Create some values of x xs = [1,2,3,4,5,6] """ Explanation: Create Some Values Of x End of explanation """ #Define argmin that def argmin(f, xs): # Applies f on all the x's data = [f(x) for x in xs] # Finds index of the smallest output of f(x) index_of_min = data.index(min(data)) # Returns the x that produced that output return xs[index_of_min] # Run the argmin function argmin(f, xs) """ Explanation: Find The Argmin Of f(x) End of explanation """ print('x','|', 'f(x)') print('--------------') for x in xs: print(x,'|', f(x)) """ Explanation: Check Our Results End of explanation """
quantopian/research_public
videos/miscellaneous/dfs/dfs_quant_finance.ipynb
apache-2.0
import pandas as pd df = local_csv('nba_data.csv') df['game_datetime'] = pd.to_datetime(df['game_date']) df = df.set_index(['game_datetime', 'player_id']) """ Explanation: Before running this notebook, run the 2 cells containing supporting functions at the bottom. Daily Fantasy Sports and Quantitative Finance A case study on using quantitative finance tools to build daily fantasy sports lineups. Daily fantasy sports (DFS) have emerged in recent years as a popular skill game. Usually, games challenge participants to pick a team of players (called a 'lineup') in a particular sport on a given day with the objective of getting the most game points on that day. In the classic DFS format, players are assigned a fictional 'salary' or cost and the DFS participant has to pick a roster of players who fit under a total cost constraint, commonly referred to as a 'salary cap'. Players are ranked at the end of the day based on a sport-dependent scoring function. In this notebook, we will take a look at how quantitative finance tools can be used to study daily fantasy sports data and build an optimal lineup using convex optimization. Specifically, we will take a look at the NBA (basketball) game on DraftKings. The data used in this notebooks is obtained from https://stats.nba.com and DraftKings (DK). The tools used are a mix of tools from the Quantopian API as well as other Python libraries. Load and Format Data The first step to most quantitative problems is to get data. In this study, the data was collected and uploaded to the Quantopian research environment as a .csv file. Let's load it into a pandas DataFrame using local_csv (a Quantopian-specific function). End of explanation """ df.head(3) """ Explanation: It is important to know what our data looks like, so here is a preview of the first few rows of our DataFrame. End of explanation """ df.iloc[10] """ Explanation: And here is a look at a single row where we can see all of the columns. End of explanation """ # Rolling 20 day mean fantasy score per game. trailing_20_dk_score = df['dk_score'].unstack().shift(1).rolling(20, min_periods=5).mean().stack() trailing_20_dk_score.head() """ Explanation: Alphalens (Factor Analysis) Alphalens is a tool on Quantopian for analyzing the predictve ability of a factor. In this notebook, we will use Alphalens to analyze the predictive ability of a fantasy points per game factor. The first step to analzing our factor is to define it. Here, we will define the fantasy points per game factor, trailing_20_dk_score to be the rolling mean fantasy points per game (using DK scoring rules) over the last 20 days. End of explanation """ # DK scores. scores = df['dk_score'].unstack() """ Explanation: And then we need to define our objective metric, or 'what we want to maximize'. In finance, we want to maximize portfolio returns. In DraftKings DFS, we want to maximize our DraftKings score for the current day. End of explanation """ import alphalens as al """ Explanation: Next, we need to import Alphalens so that we can use it to analyze our factors. End of explanation """ # Format rolling fantasy points per game data for use in Alphalens. factor_data = get_clean_factor_and_forward_scores( factor=trailing_20_dk_score, scores=scores.loc['2017-11-09':], periods=[1], ) mean_by_q_daily, std_err_by_q_daily = al.performance.mean_return_by_quantile(factor_data, by_date=True, demeaned=False) al.plotting.plot_quantile_returns_violin(mean_by_q_daily/10000); """ Explanation: Before using Alphalens, we need to format our data in a way that it expects. Let's start with our points factor. The below function creates a DataFrame using our points factor and our DK scores. It also specifies periods to be 1, meaning we only care about the performance of the player on one day. The data will be categorized into 5 'quantiles' to remove some of the noise from the relationship. Now, let's plot the relationship between each of our points per game factor quantiles and see how strongly they predict DK points on a given day. End of explanation """ quant_spread, std_err_spread = al.performance.compute_mean_returns_spread(mean_by_q_daily, upper_quant=5, lower_quant=1, std_err=std_err_by_q_daily) import matplotlib.cm as cm import matplotlib.pyplot as plt plt.figure(figsize=(14,8)) quantiles = mean_by_q_daily.index.get_level_values(0) colors = cm.rainbow(np.linspace(0, 1, len(quantiles.unique()))) for quantile in quantiles.unique(): x = mean_by_q_daily[quantiles == quantile].index.get_level_values(1) y = mean_by_q_daily[quantiles == quantile] plt.plot(x, y, color=colors[quantile-1]) ax = plt.gca() ax.legend(quantiles.unique()) ax.set_ylabel('DK Points') ax.set_xlabel('Date') plt.title('Daily Mean DK Points Per Quantile (Points Per Game Factor)') """ Explanation: It looks like our fantasy points per game factor is a strong predictor. We see a narrow and distinct distribution around each quantile's mean DK points (y axis). Let's look at another visualization of the points per game factor and plot out the daily mean of each quantile. End of explanation """ # Import the Optimize namespace. import quantopian.optimize as opt """ Explanation: Optimize (Portfolio Optimization) Now that we have identified some strong predictors of fantasy points, let's use the data to build an optimal portfolio each day. Specifically, we will pick a team of players (construct a portfolio) based on their mean points per game over the last 20 days. On Quantopian, we can use the Optimize API to help us calculate an optimal 'portfolio' each day. In finance, this means picking the stocks that we should hold each day based on an objective function and a set of constraints. In daily fantasy sports, the problem is the same: we want to pick a lineup based on an objective function (maximize DK points) subject to a series of constraints (based on the rules of the game). Generally speaking, constraints are the easy part. The rules are set before every game and we know that our lineup has to follow these rules. Specifically, the NBA game at DraftKings has the following rules: - The lineup must be composed of exactly 8 players. - The sum of the fictional player salaries in a lineup must be less than 50,000. - A lineup must include players from at least two NBA games. - A lineup must include at least one player classified in each of the following positions: - PG - SG - PF - SF - C - G (PG or SG, in addition to the other PG and SG slots) - F (PF or SF, in addition to the other PF and SF slots) - U (the last spot can be occupied by a player of any position). The challenging part is creating an objective function. We know that we want to maximize the number of DK points that we get on a given day, but without time travel, it's difficult to know exactly what the function looks like. In practice, this means we need to define an 'expected value' objective that represents our expected performance of each player. Earlier, we saw that our trailing points per game factor was a good predictor of DK points, so let's use that as our objective function. As an optimization problem, this means that we want to pick a team of players subject to the DK rules (salary cap, positions, etc.) that maximizes the total trailing points per game factor. Let's define our problem using the Optimize API. End of explanation """ # Player costs. player_costs = pd.DataFrame(df['dk_salary']).dropna().sort_index(level=['game_datetime', 'player_id']) # Player positions. player_positions = df['dk_position_codes'].dropna().apply((lambda x: [int(y) for y in x[1:-1].split(',')])) """ Explanation: Let's start by assembling and formatting the player salaries and positions so that we can use them as constraints in our optimization problem. End of explanation """ # Define the game date that we want to test. Change this and re-run # cells below to build a lineup for another date. TEST_DATE = '2017-12-01' # Format our expected value factor (trailing_20_dk_score) for use in Optimize. expected_value = trailing_20_dk_score[player_costs.index].dropna() expected_value = expected_value[expected_value.index.get_level_values(0) == TEST_DATE] """ Explanation: Then, let's restructure our (trailing_20_dk_score) so that we can use it as an objective function in Optimize. We'll define it to be parametric on the date so that we can play around with the date later on. End of explanation """ # Objective function to be fed into Optimize later on. obj = opt.MaximizeAlpha(expected_value) """ Explanation: Objective Next, let's define our objective function using optimize.MaximizeAlpha, which will try to maximize the value of our lineup based on our expected_value factor. End of explanation """ # Salary cap constraint. The total cost of our lineup has to be less than 50,000. # We will define this as a FactorExposure constraint. cost_limit = opt.FactorExposure( player_costs, min_exposures={'dk_salary': 0}, max_exposures={'dk_salary': 50000} ) """ Explanation: Constraints Many of the built-in constraints are centered around finance problems, so we will have to make some simplifying assumptions in order to use them to build our lineup. Later in the notebook, we will build our own optimizer to build a lineup that strictly follows the DK rules. Let's start by defining our salary cap constraint: End of explanation """ # Map from each player to its position. labels = df['position'].apply(lambda x: x[0]) # # Maps from each position to its min/max exposure. min_exposures = {'F': 3, 'G': 3, 'C': 1} max_exposures = {'F': 4, 'G': 4, 'C': 2} player_position_constraint = opt.NetGroupExposure(labels, min_exposures, max_exposures) """ Explanation: Next, we'll define a position constraint. To simplify things, we'll use more generic positions, and limit ourselves to a maximum of 4 forwards (F), 4 guards (G), and 2 centers (C), with a minimum of 3 F, 3 G, and 1 C. End of explanation """ # This constraints tells the Optimizer than we can hold at most 1 of each player discretize_players = opt.PositionConcentration( pd.Series([]), pd.Series([]), default_min_weight=0, default_max_weight=1, ) """ Explanation: At this point, it's worth noting that Optimize operates in weight space, meaning it chooses a percentage (not bounded by a total of 100%, can also be positive or negative) of the overall lineup to allocate to each asset/player. In an attempt to get around that, the next constraint we define will specify that we can hold no more than 1 of each player, and no fewer than 0 of each player (you can't short sell a player... yet). End of explanation """ max_players = opt.MaxGrossExposure(8) """ Explanation: Lastly, let's define a constraint for our total number of players. End of explanation """ result = opt.calculate_optimal_portfolio( objective=obj, constraints=[ discretize_players, player_position_constraint, max_players, cost_limit, ] ) """ Explanation: Calculate Optimal Portfolio (Build Lineup) The next step is to calculate our optimal portfolio for the day using our objective and constraints. End of explanation """ resulting_picks = result[(result.index.get_level_values(0) == TEST_DATE)] player_weights = resulting_picks[resulting_picks>0] lineup_info = df.loc[player_weights.index][['matchup', 'player', 'position', 'dk_salary']] lineup_info['weight'] = player_weights lineup_info """ Explanation: And here are the resulting weights: End of explanation """ # List of DK positions. DK_POSITION_LIST = ['PG', 'SG', 'PF', 'SF', 'C', 'G', 'F', 'U'] # Get the average play time for all players over the last 20 games. We will use this to # filter out players with skewed stats due to playing very little. trailing_20_mins = df['min'].unstack().shift(1).rolling(20, min_periods=5).mean().stack() # Players with non-null salary on TEST_DATE. have_salary = player_costs[player_costs.index.get_level_values(0) == TEST_DATE].dropna().index # Values from our factor for TEST_DATE. trailing_dk_score_today = trailing_20_dk_score[ (trailing_20_dk_score.index.get_level_values(0) == TEST_DATE) ] # Players with at least 5 minutes per game on average over the last 20 days. trailing_mins_today = trailing_20_mins[(trailing_20_mins.index.get_level_values(0) == TEST_DATE)] have_play_time = trailing_mins_today[trailing_mins_today >= 5].index # Eligible players for us to pick have a non-null salary and at least 5 minutes # played per game over the last 20 days. eligible_players_today = have_salary.intersection(have_play_time) # The game ID in which each player is playing. player_games = df.loc[eligible_players_today].game_id # The set of all game IDs on TEST_DATE todays_games = df.loc[eligible_players_today].game_id.unique().tolist() """ Explanation: Something that immediately pops out is the non-binary weight assigned to Kemba Walker. Obviously, it's not possible to pick 0.55% of a player in DFS, so this lineup won't be eligible to enter. Unfortunately, it's not currently possible to binarize the outputs of Optimize on Quantopian (since it's not a helpful feature in quantitative finance). CVXPY To get around the limits of Optimize, we can take a similar approach and use cvxpy, a Python library for solving convex optimization problems (and the library on top of which Optimize was built), to build our own objective and constraints. In this version, we will follow the exact rules of the DraftKings NBA game (8 players, \$50k salary cap, players in at least two games, and one player in each of the following positions: ['PG', 'SG', 'PF', 'SF', 'C', 'G', 'F', 'U']. The following cells build constraints to enforce these rules. End of explanation """ import cvxpy as cvx # Player salaries and expected values. salaries = np.squeeze(np.array(player_costs.loc[eligible_players_today])) values = np.array(expected_value[eligible_players_today]) # The variable we are solving for. We define our output variable as a Bool # since we have to make a binary decision on each player (pick or don't pick). selection = cvx.Bool(len(salaries)) selection.is_positive = new_is_positive # Our lineup's total salary must be less than 50,000. salary_cap = 50000 cost_constraint = salaries * selection <= salary_cap # Our lineup must be composed of exactly 8 players. player_constraint = np.ones(len(salaries)) * selection == 8 # Our total expected value is the sum of the value of each player in # the lineup. We define our objective to maximize the total expected # value. total_expected_value = values * selection objective = cvx.Maximize(total_expected_value) # Put our cost and player count constraints in a list. constraints = [cost_constraint, player_constraint] # Define our position constraints. Positions are represented along an 8-element # array corresponding to the positions in DK_POSITION_LIST. position_min = np.array([1, 1, 1, 1, 1, 3, 3, 8]) pos_limits = {} i = 0 for pos in DK_POSITION_LIST: pos_limits[pos] = np.array(player_positions[eligible_players_today].apply(lambda x: x[i])) constraints.append((pos_limits[pos] * selection) >= position_min[i]) i += 1 # Define our game constraints. We rephrase the rule as 'you cannot pick more than # 7 players from any one game'. for gid in todays_games: game_limit = np.array(player_games == gid) constraints.append((game_limit * selection) <= 7) # We tell cvxpy that we want maximize our expected value, subject to all # of our constraints. optimization_problem = cvx.Problem(objective, constraints) print "Our total expected value from today's lineup is:" # Solving the problem. optimization_problem.solve(solver=cvx.ECOS_BB) """ Explanation: Next, we will import cvxpy and define our objective and constraints. End of explanation """ # Format output and get relevant player info for display. dk_team = pd.Series(np.squeeze(selection.value).tolist()[0]) player_info = df.loc[player_costs.loc[eligible_players_today].iloc[dk_team[dk_team > 0.1].index.values].index][['matchup', 'player', 'dk_position', 'dk_salary', 'dk_score']] player_info print "Total lineup salary: %d" % player_info['dk_salary'].sum() print "Total actual score: %d" % player_info['dk_score'].sum() """ Explanation: Based on our player-by-player expected values and the constraints we supplied to cvxpy, our optimal lineup has a total expected value of 273.37. Let's take a look at who is in this lineup to make sure that we implemented the rules properly: End of explanation """ def backtest(factor, dates, filters, df, player_costs, player_positions): historical_results = {} daily_expected_value = factor[filters].dropna() for _date in dates: try: print _date daily_filter = filters[filters.get_level_values(0) == _date] expected_value_today = daily_expected_value[daily_expected_value.index.get_level_values(0) == _date] # The game ID in which each player is playing. player_games = df.loc[daily_filter].game_id # The set of all game IDs on the current date. todays_games = df.loc[daily_filter].game_id.unique().tolist() # Player salaries and expected values. salaries = np.squeeze(np.array(player_costs.loc[daily_filter])) values = np.array(expected_value_today[daily_filter]) # The variable we are solving for. We define our output variable as a Bool # since we have to make a binary decision on each player (pick or don't pick). selection = cvx.Bool(len(salaries)) selection.is_positive = new_is_positive # Our lineup's total salary must be less than 50,000. salary_cap = 50000 cost_constraint = salaries * selection <= salary_cap # Our lineup must be composed of exactly 8 players. player_constraint = np.ones(len(salaries)) * selection == 8 # Our total expected value is the sum of the value of each player in # the lineup. We define our objective to maximize the total expected # value. total_expected_value = values * selection objective = cvx.Maximize(total_expected_value) # Put our cost and player count constraints in a list. constraints = [cost_constraint, player_constraint] # Define our position constraints. Positions are represented along an 8-element # array corresponding to the positions in DK_POSITION_LIST. position_min = np.array([1, 1, 1, 1, 1, 3, 3, 8]) pos_limits = {} i = 0 for pos in DK_POSITION_LIST: pos_limits[pos] = np.array(player_positions[daily_filter].apply(lambda x: x[i])) constraints.append((pos_limits[pos] * selection) >= position_min[i]) i += 1 # Define our game constraints. We rephrase the rule as 'you cannot pick more than # 7 players from any one game'. for gid in todays_games: game_limit = np.array(player_games == gid) constraints.append((game_limit * selection) <= 7) # We tell cvxpy that we want maximize our expected value, subject to all # of our constraints. knapsack_problem = cvx.Problem(objective, constraints) # Solving the problem. predicted_value = knapsack_problem.solve(solver=cvx.ECOS_BB) dk_team = pd.Series(np.squeeze(selection.value).tolist()[0]) player_info = df.loc[player_costs.loc[filters].iloc[dk_team[dk_team > 0.1].index.values].index][['matchup', 'player', 'dk_position', 'dk_salary', 'dk_score']] historical_results[_date] = { 'actual_score': player_info.dk_score.sum(), 'expected_score': predicted_value, } except TypeError: pass except ValueError: pass return historical_results test_dates = trailing_20_dk_score.index.get_level_values(0).unique().values[15:] has_playtime = trailing_20_mins[trailing_20_mins >= 5] filters = player_costs.index & has_playtime.index backtest_result = backtest( trailing_20_dk_score, test_dates, filters, df, player_costs, player_positions, ) daily_results = pd.DataFrame.from_dict(backtest_result, orient='index') print daily_results.mean() daily_results.plot(); """ Explanation: Our roster appears to satisfy the rules! Backtest (a.k.a. run the above code over several consecutive days) End of explanation """ import numpy as np from pandas.tseries.offsets import CustomBusinessDay from scipy.stats import mode def compute_forward_scores(factor, scores, periods=(1, 5, 10), filter_zscore=None): """ Finds the N period forward returns (as percent change) for each asset provided. Parameters ---------- factor : pd.Series - MultiIndex A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor. - See full explanation in utils.get_clean_factor_and_forward_returns scores : pd.DataFrame Pricing data to use in forward price calculation. Assets as columns, dates as index. Pricing data must span the factor analysis time period plus an additional buffer window that is greater than the maximum number of expected periods in the forward returns calculations. periods : sequence[int] periods to compute forward returns on. filter_zscore : int or float, optional Sets forward returns greater than X standard deviations from the the mean to nan. Set it to 'None' to avoid filtering. Caution: this outlier filtering incorporates lookahead bias. Returns ------- forward_returns : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by timestamp (level 0) and asset (level 1), containing the forward returns for assets. Forward returns column names follow the format accepted by pd.Timedelta (e.g. '1D', '30m', '3h15m', '1D1h', etc). 'date' index freq property (forward_returns.index.levels[0].freq) will be set to a trading calendar (pandas DateOffset) inferred from the input data (see infer_trading_calendar for more details). """ factor_dateindex = factor.index.levels[0] if factor_dateindex.tz != scores.index.tz: raise NonMatchingTimezoneError("The timezone of 'factor' is not the " "same as the timezone of 'scores'. See " "the pandas methods tz_localize and " "tz_convert.") freq = infer_trading_calendar(factor_dateindex, scores.index) factor_dateindex = factor_dateindex.intersection(scores.index) if len(factor_dateindex) == 0: raise ValueError("Factor and scores indices don't match: make sure " "they have the same convention in terms of datetimes " "and symbol-names") forward_returns = pd.DataFrame(index=pd.MultiIndex.from_product( [factor_dateindex, scores.columns], names=['date', 'asset'])) forward_returns.index.levels[0].freq = freq for period in sorted(periods): # # build forward returns # fwdret = (scores #.shift(-period) .reindex(factor_dateindex) ) if filter_zscore is not None: mask = abs(fwdret - fwdret.mean()) > (filter_zscore * fwdret.std()) fwdret[mask] = np.nan # Find the period length, which will be the column name # Becase the calendar inferred from factor and prices doesn't take # into consideration holidays yet, there could be some non-trading days # in between the trades so we'll test several entries to find out the # correct period length # entries_to_test = min(10, len(fwdret.index), len(scores.index)-period) days_diffs = [] for i in range(entries_to_test): p_idx = scores.index.get_loc(fwdret.index[i]) start = scores.index[p_idx] end = scores.index[p_idx+period] period_len = diff_custom_calendar_timedeltas(start, end, freq) days_diffs.append(period_len.components.days) delta_days = period_len.components.days - mode(days_diffs).mode[0] period_len -= pd.Timedelta(days=delta_days) # Finally use period_len as column name column_name = timedelta_to_string(period_len) forward_returns[column_name] = fwdret.stack() forward_returns.index = forward_returns.index.rename(['date', 'asset']) return forward_returns def get_clean_factor_and_forward_scores(factor, scores, groupby=None, binning_by_group=False, quantiles=5, bins=None, periods=(1, 5, 10), filter_zscore=20, groupby_labels=None, max_loss=10.0): forward_scores = compute_forward_scores(factor, scores, periods, filter_zscore) factor_data = get_clean_factor(factor, forward_scores, groupby=groupby, groupby_labels=groupby_labels, quantiles=quantiles, bins=bins, binning_by_group=binning_by_group, max_loss=max_loss) return factor_data def infer_trading_calendar(factor_idx, prices_idx): """ Infer the trading calendar from factor and price information. Parameters ---------- factor_idx : pd.DatetimeIndex The factor datetimes for which we are computing the forward returns prices_idx : pd.DatetimeIndex The prices datetimes associated withthe factor data Returns ------- calendar : pd.DateOffset """ full_idx = factor_idx.union(prices_idx) # drop days of the week that are not used days_to_keep = [] days_of_the_week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] for day, day_str in enumerate(days_of_the_week): if (full_idx.dayofweek == day).any(): days_to_keep.append(day_str) days_to_keep = ' '.join(days_to_keep) # we currently don't infer holidays, but CustomBusinessDay class supports # custom holidays. So holidays could be inferred too eventually return CustomBusinessDay(weekmask=days_to_keep) def diff_custom_calendar_timedeltas(start, end, freq): """ Compute the difference between two pd.Timedelta taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- start : pd.Timestamp end : pd.Timestamp freq : DateOffset, optional Returns ------- pd.Timedelta end - start """ actual_days = pd.date_range(start, end, freq=freq).shape[0] - 1 timediff = end - start delta_days = timediff.components.days - actual_days return timediff - pd.Timedelta(days=delta_days) def get_clean_factor(factor, forward_returns, groupby=None, binning_by_group=False, quantiles=5, bins=None, groupby_labels=None, max_loss=0.35): """ Formats the factor data, forward return data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens functionalities as long as the factor data conforms to the format returned from get_clean_factor_and_forward_returns and documented here Parameters ---------- factor : pd.Series - MultiIndex A MultiIndex Series indexed by timestamp (level 0) and asset (level 1), containing the values for a single alpha factor. :: ----------------------------------- date | asset | ----------------------------------- | AAPL | 0.5 ----------------------- | BA | -1.1 ----------------------- 2014-01-01 | CMG | 1.7 ----------------------- | DAL | -0.1 ----------------------- | LULU | 2.7 ----------------------- forward_returns : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by timestamp (level 0) and asset (level 1), containing the forward returns for assets. Forward returns column names must follow the format accepted by pd.Timedelta (e.g. '1D', '30m', '3h15m', '1D1h', etc). 'date' index freq property must be set to a trading calendar (pandas DateOffset), see infer_trading_calendar for more details. This information is currently used only in cumulative returns computation :: --------------------------------------- | | 1D | 5D | 10D --------------------------------------- date | asset | | | --------------------------------------- | AAPL | 0.09|-0.01|-0.079 ---------------------------- | BA | 0.02| 0.06| 0.020 ---------------------------- 2014-01-01 | CMG | 0.03| 0.09| 0.036 ---------------------------- | DAL |-0.02|-0.06|-0.029 ---------------------------- | LULU |-0.03| 0.05|-0.009 ---------------------------- groupby : pd.Series - MultiIndex or dict Either A MultiIndex Series indexed by date and asset, containing the period wise group codes for each asset, or a dict of asset to group mappings. If a dict is passed, it is assumed that group mappings are unchanged for the entire time period of the passed factor data. binning_by_group : bool If True, compute quantile buckets separately for each group. This is useful when the factor values range vary considerably across gorups so that it is wise to make the binning group relative. You should probably enable this if the factor is intended to be analyzed for a group neutral portfolio quantiles : int or sequence[float] Number of equal-sized quantile buckets to use in factor bucketing. Alternately sequence of quantiles, allowing non-equal-sized buckets e.g. [0, .10, .5, .90, 1.] or [.05, .5, .95] Only one of 'quantiles' or 'bins' can be not-None bins : int or sequence[float] Number of equal-width (valuewise) bins to use in factor bucketing. Alternately sequence of bin edges allowing for non-uniform bin width e.g. [-4, -2, -0.5, 0, 10] Chooses the buckets to be evenly spaced according to the values themselves. Useful when the factor contains discrete values. Only one of 'quantiles' or 'bins' can be not-None groupby_labels : dict A dictionary keyed by group code with values corresponding to the display name for each group. max_loss : float, optional Maximum percentage (0.00 to 1.00) of factor data dropping allowed, computed comparing the number of items in the input factor index and the number of items in the output DataFrame index. Factor data can be partially dropped due to being flawed itself (e.g. NaNs), not having provided enough price data to compute forward returns for all factor values, or because it is not possible to perform binning. Set max_loss=0 to avoid Exceptions suppression. Returns ------- merged_data : pd.DataFrame - MultiIndex A MultiIndex Series indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - forward returns column names follow the format accepted by pd.Timedelta (e.g. '1D', '30m', '3h15m', '1D1h', etc) - 'date' index freq property (merged_data.index.levels[0].freq) is the same as that of the input forward returns data. This is currently used only in cumulative returns computation :: ------------------------------------------------------------------- | | 1D | 5D | 10D |factor|group|factor_quantile ------------------------------------------------------------------- date | asset | | | | | | ------------------------------------------------------------------- | AAPL | 0.09|-0.01|-0.079| 0.5 | G1 | 3 -------------------------------------------------------- | BA | 0.02| 0.06| 0.020| -1.1 | G2 | 5 -------------------------------------------------------- 2014-01-01 | CMG | 0.03| 0.09| 0.036| 1.7 | G2 | 1 -------------------------------------------------------- | DAL |-0.02|-0.06|-0.029| -0.1 | G3 | 5 -------------------------------------------------------- | LULU |-0.03| 0.05|-0.009| 2.7 | G1 | 2 -------------------------------------------------------- """ initial_amount = float(len(factor.index)) factor = factor.copy() factor.index = factor.index.rename(['date', 'asset']) merged_data = forward_returns.copy() merged_data['factor'] = factor if groupby is not None: if isinstance(groupby, dict): diff = set(factor.index.get_level_values( 'asset')) - set(groupby.keys()) if len(diff) > 0: raise KeyError( "Assets {} not in group mapping".format( list(diff))) ss = pd.Series(groupby) groupby = pd.Series(index=factor.index, data=ss[factor.index.get_level_values( 'asset')].values) if groupby_labels is not None: diff = set(groupby.values) - set(groupby_labels.keys()) if len(diff) > 0: raise KeyError( "groups {} not in passed group names".format( list(diff))) sn = pd.Series(groupby_labels) groupby = pd.Series(index=groupby.index, data=sn[groupby.values].values) merged_data['group'] = groupby.astype('category') merged_data = merged_data.dropna() fwdret_amount = float(len(merged_data.index)) no_raise = False if max_loss == 0 else True merged_data['factor_quantile'] = quantize_factor(merged_data, quantiles, bins, binning_by_group, no_raise) merged_data = merged_data.dropna() binning_amount = float(len(merged_data.index)) tot_loss = (initial_amount - binning_amount) / initial_amount fwdret_loss = (initial_amount - fwdret_amount) / initial_amount bin_loss = tot_loss - fwdret_loss # print("Dropped %.1f%% entries from factor data: %.1f%% in forward " # "returns computation and %.1f%% in binning phase " # "(set max_loss=0 to see potentially suppressed Exceptions)." % # (tot_loss * 100, fwdret_loss * 100, bin_loss * 100)) if tot_loss > max_loss: message = ("max_loss (%.1f%%) exceeded %.1f%%, consider increasing it." % (max_loss * 100, tot_loss * 100)) raise MaxLossExceededError(message) else: # print("max_loss is %.1f%%, not exceeded: OK!" % (max_loss * 100)) pass return merged_data def timedelta_to_string(timedelta): """ Utility that converts a pandas.Timedelta to a string representation compatible with pandas.Timedelta constructor format Parameters ---------- timedelta: pd.Timedelta Returns ------- string string representation of 'timedelta' """ c = timedelta.components format = '' if c.days != 0: format += '%dD' % c.days if c.hours > 0: format += '%dh' % c.hours if c.minutes > 0: format += '%dm' % c.minutes if c.seconds > 0: format += '%ds' % c.seconds if c.milliseconds > 0: format += '%dms' % c.milliseconds if c.microseconds > 0: format += '%dus' % c.microseconds if c.nanoseconds > 0: format += '%dns' % c.nanoseconds return format def add_custom_calendar_timedelta(inputs, timedelta, freq): """ Add timedelta to 'input' taking into consideration custom frequency, which is used to deal with custom calendars, such as a trading calendar Parameters ---------- input : pd.DatetimeIndex or pd.Timestamp timedelta : pd.Timedelta freq : DateOffset, optional Returns ------- pd.DatetimeIndex or pd.Timestamp input + timedelta """ days = timedelta.components.days offset = timedelta - pd.Timedelta(days=days) return inputs + freq * days + offset def non_unique_bin_edges_error(func): """ Give user a more informative error in case it is not possible to properly calculate quantiles on the input dataframe (factor) """ message = """ An error occurred while computing bins/quantiles on the input provided. This usually happens when the input contains too many identical values and they span more than one quantile. The quantiles are choosen to have the same number of records each, but the same value cannot span multiple quantiles. Possible workarounds are: 1 - Decrease the number of quantiles 2 - Specify a custom quantiles range, e.g. [0, .50, .75, 1.] to get unequal number of records per quantile 3 - Use 'bins' option instead of 'quantiles', 'bins' chooses the buckets to be evenly spaced according to the values themselves, while 'quantiles' forces the buckets to have the same number of records. 4 - for factors with discrete values use the 'bins' option with custom ranges and create a range for each discrete value Please see utils.get_clean_factor_and_forward_returns documentation for full documentation of 'bins' and 'quantiles' options. """ def dec(*args, **kwargs): try: return func(*args, **kwargs) except ValueError as e: if 'Bin edges must be unique' in str(e): rethrow(e, message) raise return dec @non_unique_bin_edges_error def quantize_factor(factor_data, quantiles=5, bins=None, by_group=False, no_raise=False): """ Computes period wise factor quantiles. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single alpha factor, forward returns for each period, the factor quantile/bin that factor value belongs to, and (optionally) the group the asset belongs to. - See full explanation in utils.get_clean_factor_and_forward_returns quantiles : int or sequence[float] Number of equal-sized quantile buckets to use in factor bucketing. Alternately sequence of quantiles, allowing non-equal-sized buckets e.g. [0, .10, .5, .90, 1.] or [.05, .5, .95] Only one of 'quantiles' or 'bins' can be not-None bins : int or sequence[float] Number of equal-width (valuewise) bins to use in factor bucketing. Alternately sequence of bin edges allowing for non-uniform bin width e.g. [-4, -2, -0.5, 0, 10] Only one of 'quantiles' or 'bins' can be not-None by_group : bool If True, compute quantile buckets separately for each group. no_raise: bool, optional If True, no exceptions are thrown and the values for which the exception would have been thrown are set to np.NaN Returns ------- factor_quantile : pd.Series Factor quantiles indexed by date and asset. """ if not ((quantiles is not None and bins is None) or (quantiles is None and bins is not None)): raise ValueError('Either quantiles or bins should be provided') def quantile_calc(x, _quantiles, _bins, _no_raise): try: if _quantiles is not None and _bins is None: return pd.qcut(x, _quantiles, labels=False) + 1 elif _bins is not None and _quantiles is None: return pd.cut(x, _bins, labels=False) + 1 except Exception as e: if _no_raise: return pd.Series(index=x.index) raise e grouper = [factor_data.index.get_level_values('date')] if by_group: grouper.append('group') factor_quantile = factor_data.groupby(grouper)['factor'] \ .apply(quantile_calc, quantiles, bins, no_raise) factor_quantile.name = 'factor_quantile' return factor_quantile.dropna() def new_is_positive(): return False """ Explanation: Conclusion In this notebook, we looked at daily fantasy sports using quantitative finance tools. We started out by pulling in and looking at NBA data. We created and tested the ability of certain statistics to predict DK points using Alphalens. We attempted to build an optimal lineup using Optimize. And lastly, we used cvxpy to build a proper solution to the daily lineup construction problem. Future Work In both quantitative finance and daily fantasy sports, the hardest problem is forecasting results of an asset or player in the future. Now that we have a notebook built to help us test factors and build lineups, the next step is to iterate on ideas of predictive signals. In this example, we only looked at two relatively simple metrics (minutes played and points scored). It would be interesting to try new factors to see if they are predictive or provide a leg up on the competitiong. Another area that we didn't explore in this notebook is risk. In most team sports, the measured statistics of one player tend to be correlated (positively or negatively) with other players in the game. For example, players might get fantasy points for getting an assist when a teammate scores. These correlations can be defined as risk factors. Risk factors can be exploited or hedged depending on the desired risk profile of the lineup. The objective function or constraints in the optimization problem could be altered to either try to exploit or hedge risk. Helper Functions - Cells Below Need to Be Run at Notebook Start End of explanation """
graphistry/pygraphistry
demos/demos_databases_apis/gpu_rapids/part_ii_gpu_cudf.ipynb
bsd-3-clause
#!pip install graphistry -q import pandas as pd import numpy as np import cudf import graphistry graphistry.__version__ # To specify Graphistry account & server, use: # graphistry.register(api=3, username='...', password='...', protocol='https', server='hub.graphistry.com') # For more options, see https://github.com/graphistry/pygraphistry#configure """ Explanation: Visual GPU Log Analytics Part II: GPU dataframes with RAPIDS Python cudf bindings Graphistry is great -- Graphistry and RAPIDS/BlazingDB is better! This tutorial series visually analyzes Zeek/Bro network connection logs using different compute engines: Part I: CPU Baseline in Python Pandas Part II: GPU Dataframe with RAPIDS Python cudf bindings Part II Contents: Time using GPU-based RAPIDS Python cudf bindings and Graphistry for a full ETL & visual analysis flow: Load data Analyze data Visualize data TIP: If you get out of memory errors, you usually must restart the kernel & refresh the page End of explanation """ %%time !curl https://www.secrepo.com/maccdc2012/conn.log.gz | gzip -d > conn.log !head -n 3 conn.log # OPTIONAL: For slow devices, work on a subset #!awk 'NR % 20 == 0' < conn.log > conn-5pc.log #!awk 'NR % 100 == 0' < conn.log > conn-1pc.log #!nvidia-smi cdf = cudf.read_csv("./conn.log", sep="\t", header=None, names=["time", "uid", "id.orig_h", "id.orig_p", "id.resp_h", "id.resp_p", "proto", "service", "duration", "orig_bytes", "resp_bytes", "conn_state", "local_orig", "missed_bytes", "history", "orig_pkts", "orig_ip_bytes", "resp_pkts", "resp_ip_bytes", "tunnel_parents"], dtype=['date', 'str', 'str', 'int', 'str', 'int', 'str', 'str', 'int', 'int', 'int', 'str', 'str', 'int', 'str', 'int', 'int', 'int', 'int', 'str'], na_values=['-'], index_col=False) #fillna for c in cdf.columns: if c in ['uid', 'id.orig_h', 'id.resp_h', 'proto', 'service', 'conn_state', 'history', 'tunnel_parents', 'local_orig']: continue cdf[c] = cdf[c].fillna(0) print('# rows', len(cdf)) cdf.head(3) """ Explanation: 1. Load data End of explanation """ LIMIT = 12000000 cdf_summary = cdf\ .head(LIMIT)\ .apply_rows( sum_bytes, incols=['orig_bytes', 'resp_bytes'], outcols=dict(sum_bytes=np.int64), kwargs=dict())\ .groupby(['id.orig_h', 'id.resp_h', 'conn_state'])\ .agg({ 'time': ['min', 'max', 'count'], 'id.resp_p': ['count'], 'uid': ['count'], 'duration': ['min', 'max', 'mean'], 'orig_bytes': ['min', 'max', 'sum', 'mean'], 'resp_bytes': ['min', 'max', 'sum', 'mean'], 'sum_bytes': ['min', 'max', 'sum', 'mean'] }) print('# rows', len(cdf_summary)) cdf_summary.head(3).to_pandas() """ Explanation: 2. Analyze Data Summarize network activities between every communicating src/dst IP, split by connection state RAPIDS currently fails when exceeding GPU memory, so limit workload size as needed End of explanation """ hg = graphistry.hypergraph( cdf_summary.to_pandas(), ['id.orig_h', 'id.resp_h'], direct=True, opts={ 'CATEGORIES': { 'ip': ['id.orig_h', 'id.resp_h'] } }) hg['graph'].plot() """ Explanation: 3. Visualize data Nodes: IPs Bigger when more sessions (split by connection state) involving them Edges: src_ip -> dest_ip, split by connection state End of explanation """
shreyas111/Multimedia_CS523_Project1
Style_Transfer_Without_Style_Loss.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import PIL.Image """ Explanation: Style Transfer Our Changes: We have modified the code in such a way that the style loss and the gram matrices are not calculated. The algorithm only runs on content loss and the denoise loss. Thus the styles are not transferred to the mixed image. The mixed images only shows content features and is devoid of noise. Imports End of explanation """ tf.__version__ import vgg16 """ Explanation: This was developed using Python 3.5.2 (Anaconda) and TensorFlow version: End of explanation """ # vgg16.data_dir = 'vgg16/' vgg16.maybe_download() """ Explanation: The VGG-16 model is downloaded from the internet. This is the default directory where you want to save the data-files. The directory will be created if it does not exist. End of explanation """ def load_image(filename, max_size=None): image = PIL.Image.open(filename) if max_size is not None: # Calculate the appropriate rescale-factor for # ensuring a max height and width, while keeping # the proportion between them. factor = max_size / np.max(image.size) # Scale the image's height and width. size = np.array(image.size) * factor # The size is now floating-point because it was scaled. # But PIL requires the size to be integers. size = size.astype(int) # Resize the image. image = image.resize(size, PIL.Image.LANCZOS) print(image) # Convert to numpy floating-point array. return np.float32(image) """ Explanation: Helper-functions for image manipulation This function loads an image and returns it as a numpy array of floating-points. The image can be automatically resized so the largest of the height or width equals max_size. End of explanation """ def save_image(image, filename): # Ensure the pixel-values are between 0 and 255. image = np.clip(image, 0.0, 255.0) # Convert to bytes. image = image.astype(np.uint8) # Write the image-file in jpeg-format. with open(filename, 'wb') as file: PIL.Image.fromarray(image).save(file, 'jpeg') """ Explanation: Save an image as a jpeg-file. The image is given as a numpy array with pixel-values between 0 and 255. End of explanation """ def plot_image_big(image): # Ensure the pixel-values are between 0 and 255. image = np.clip(image, 0.0, 255.0) # Convert pixels to bytes. image = image.astype(np.uint8) # Convert to a PIL-image and display it. display(PIL.Image.fromarray(image)) def plot_images(content_image, style_image, mixed_image): # Create figure with sub-plots. fig, axes = plt.subplots(1, 3, figsize=(10, 10)) # Adjust vertical spacing. fig.subplots_adjust(hspace=0.1, wspace=0.1) # Use interpolation to smooth pixels? smooth = True # Interpolation type. if smooth: interpolation = 'sinc' else: interpolation = 'nearest' # Plot the content-image. # Note that the pixel-values are normalized to # the [0.0, 1.0] range by dividing with 255. ax = axes.flat[0] ax.imshow(content_image / 255.0, interpolation=interpolation) ax.set_xlabel("Content") # Plot the mixed-image. ax = axes.flat[1] ax.imshow(mixed_image / 255.0, interpolation=interpolation) ax.set_xlabel("Mixed") # Plot the style-image ax = axes.flat[2] ax.imshow(style_image / 255.0, interpolation=interpolation) ax.set_xlabel("Style") # Remove ticks from all the plots. for ax in axes.flat: ax.set_xticks([]) ax.set_yticks([]) # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show() """ Explanation: This function plots a large image. The image is given as a numpy array with pixel-values between 0 and 255. This function plots the content-, mixed- and style-images. End of explanation """ def mean_squared_error(a, b): return tf.reduce_mean(tf.square(a - b)) def create_content_loss(session, model, content_image, layer_ids): """ Create the loss-function for the content-image. Parameters: session: An open TensorFlow session for running the model's graph. model: The model, e.g. an instance of the VGG16-class. content_image: Numpy float array with the content-image. layer_ids: List of integer id's for the layers to use in the model. """ # Create a feed-dict with the content-image. feed_dict = model.create_feed_dict(image=content_image) # Get references to the tensors for the given layers. layers = model.get_layer_tensors(layer_ids) # Calculate the output values of those layers when # feeding the content-image to the model. values = session.run(layers, feed_dict=feed_dict) # Set the model's graph as the default so we can add # computational nodes to it. It is not always clear # when this is necessary in TensorFlow, but if you # want to re-use this code then it may be necessary. with model.graph.as_default(): # Initialize an empty list of loss-functions. layer_losses = [] # For each layer and its corresponding values # for the content-image. for value, layer in zip(values, layers): # These are the values that are calculated # for this layer in the model when inputting # the content-image. Wrap it to ensure it # is a const - although this may be done # automatically by TensorFlow. value_const = tf.constant(value) # The loss-function for this layer is the # Mean Squared Error between the layer-values # when inputting the content- and mixed-images. # Note that the mixed-image is not calculated # yet, we are merely creating the operations # for calculating the MSE between those two. loss = mean_squared_error(layer, value_const) # Add the loss-function for this layer to the # list of loss-functions. layer_losses.append(loss) # The combined loss for all layers is just the average. # The loss-functions could be weighted differently for # each layer. You can try it and see what happens. total_loss = tf.reduce_mean(layer_losses) return total_loss def gram_matrix(tensor): shape = tensor.get_shape() # Get the number of feature channels for the input tensor, # which is assumed to be from a convolutional layer with 4-dim. num_channels = int(shape[3]) # Reshape the tensor so it is a 2-dim matrix. This essentially # flattens the contents of each feature-channel. matrix = tf.reshape(tensor, shape=[-1, num_channels]) # Calculate the Gram-matrix as the matrix-product of # the 2-dim matrix with itself. This calculates the # dot-products of all combinations of the feature-channels. gram = tf.matmul(tf.transpose(matrix), matrix) return gram def create_style_loss(session, model, style_image, layer_ids): """ Create the loss-function for the style-image. Parameters: session: An open TensorFlow session for running the model's graph. model: The model, e.g. an instance of the VGG16-class. style_image: Numpy float array with the style-image. layer_ids: List of integer id's for the layers to use in the model. """ # Create a feed-dict with the style-image. feed_dict = model.create_feed_dict(image=style_image) # Get references to the tensors for the given layers. layers = model.get_layer_tensors(layer_ids) layerIdCount=len(layer_ids) print('count of layer ids:',layerIdCount) # Set the model's graph as the default so we can add # computational nodes to it. It is not always clear # when this is necessary in TensorFlow, but if you # want to re-use this code then it may be necessary. with model.graph.as_default(): # Construct the TensorFlow-operations for calculating # the Gram-matrices for each of the layers. gram_layers = [gram_matrix(layer) for layer in layers] # Calculate the values of those Gram-matrices when # feeding the style-image to the model. values = session.run(gram_layers, feed_dict=feed_dict) # Initialize an empty list of loss-functions. layer_losses = [] # For each Gram-matrix layer and its corresponding values. for value, gram_layer in zip(values, gram_layers): # These are the Gram-matrix values that are calculated # for this layer in the model when inputting the # style-image. Wrap it to ensure it is a const, # although this may be done automatically by TensorFlow. value_const = tf.constant(value) # The loss-function for this layer is the # Mean Squared Error between the Gram-matrix values # for the content- and mixed-images. # Note that the mixed-image is not calculated # yet, we are merely creating the operations # for calculating the MSE between those two. loss = mean_squared_error(gram_layer, value_const) # Add the loss-function for this layer to the # list of loss-functions. layer_losses.append(loss) # The combined loss for all layers is just the average. # The loss-functions could be weighted differently for # each layer. You can try it and see what happens. total_loss = tf.reduce_mean(layer_losses) return total_loss def create_denoise_loss(model): loss = tf.reduce_sum(tf.abs(model.input[:,1:,:,:] - model.input[:,:-1,:,:])) + \ tf.reduce_sum(tf.abs(model.input[:,:,1:,:] - model.input[:,:,:-1,:])) return loss def style_transfer(content_image, style_image, content_layer_ids, style_layer_ids, weight_content=1.5, weight_style=10.0, weight_denoise=0.3, num_iterations=120, step_size=10.0): """ Use gradient descent to find an image that minimizes the loss-functions of the content-layers and style-layers. This should result in a mixed-image that resembles the contours of the content-image, and resembles the colours and textures of the style-image. Parameters: content_image: Numpy 3-dim float-array with the content-image. style_image: Numpy 3-dim float-array with the style-image. content_layer_ids: List of integers identifying the content-layers. style_layer_ids: List of integers identifying the style-layers. weight_content: Weight for the content-loss-function. weight_style: Weight for the style-loss-function. weight_denoise: Weight for the denoising-loss-function. num_iterations: Number of optimization iterations to perform. step_size: Step-size for the gradient in each iteration. """ # Create an instance of the VGG16-model. This is done # in each call of this function, because we will add # operations to the graph so it can grow very large # and run out of RAM if we keep using the same instance. model = vgg16.VGG16() # Create a TensorFlow-session. session = tf.InteractiveSession(graph=model.graph) # Print the names of the content-layers. print("Content layers:") print(model.get_layer_names(content_layer_ids)) print('Content Layers:',content_layer_ids) print() # Print the names of the style-layers. print("Style layers:") print(model.get_layer_names(style_layer_ids)) print('Style Layers:',style_layer_ids) print() #Printing the input paramenter to the function print('Weight Content:',weight_content) #print('Weight Style:',weight_style) print('Weight Denoise:',weight_denoise) print('Number of Iterations:',num_iterations) print('Step Size:',step_size) print() # Create the loss-function for the content-layers and -image. loss_content = create_content_loss(session=session, model=model, content_image=content_image, layer_ids=content_layer_ids) # Create the loss-function for the style-layers and -image. #loss_style = create_style_loss(session=session, # model=model, # style_image=style_image, # layer_ids=style_layer_ids) # Create the loss-function for the denoising of the mixed-image. loss_denoise = create_denoise_loss(model) # Create TensorFlow variables for adjusting the values of # the loss-functions. This is explained below. adj_content = tf.Variable(1e-10, name='adj_content') #adj_style = tf.Variable(1e-10, name='adj_style') adj_denoise = tf.Variable(1e-10, name='adj_denoise') # Initialize the adjustment values for the loss-functions. session.run([adj_content.initializer, #adj_style.initializer, adj_denoise.initializer]) # Create TensorFlow operations for updating the adjustment values. # These are basically just the reciprocal values of the # loss-functions, with a small value 1e-10 added to avoid the # possibility of division by zero. update_adj_content = adj_content.assign(1.0 / (loss_content + 1e-10)) #update_adj_style = adj_style.assign(1.0 / (loss_style + 1e-10)) update_adj_denoise = adj_denoise.assign(1.0 / (loss_denoise + 1e-10)) # This is the weighted loss-function that we will minimize # below in order to generate the mixed-image. # Because we multiply the loss-values with their reciprocal # adjustment values, we can use relative weights for the # loss-functions that are easier to select, as they are # independent of the exact choice of style- and content-layers. #loss_combined = weight_content * adj_content * loss_content + \ # weight_style * adj_style * loss_style + \ # weight_denoise * adj_denoise * loss_denoise loss_combined = weight_content * adj_content * loss_content + \ weight_denoise * adj_denoise * loss_denoise # Use TensorFlow to get the mathematical function for the # gradient of the combined loss-function with regard to # the input image. gradient = tf.gradients(loss_combined, model.input) # List of tensors that we will run in each optimization iteration. #run_list = [gradient, update_adj_content, update_adj_style, \ # update_adj_denoise] run_list = [gradient, update_adj_content, \ update_adj_denoise] # The mixed-image is initialized with random noise. # It is the same size as the content-image. mixed_image = np.random.rand(*content_image.shape) + 128 for i in range(num_iterations): # Create a feed-dict with the mixed-image. feed_dict = model.create_feed_dict(image=mixed_image) # Use TensorFlow to calculate the value of the # gradient, as well as updating the adjustment values. #grad, adj_content_val, adj_style_val, adj_denoise_val \ #= session.run(run_list, feed_dict=feed_dict) grad, adj_content_val, adj_denoise_val \ = session.run(run_list, feed_dict=feed_dict) # Reduce the dimensionality of the gradient. grad = np.squeeze(grad) # Scale the step-size according to the gradient-values. step_size_scaled = step_size / (np.std(grad) + 1e-8) # Update the image by following the gradient. mixed_image -= grad * step_size_scaled # Ensure the image has valid pixel-values between 0 and 255. mixed_image = np.clip(mixed_image, 0.0, 255.0) # Print a little progress-indicator. print(". ", end="") # Display status once every 10 iterations, and the last. if (i % 10 == 0) or (i == num_iterations - 1): print() print("Iteration:", i) #Print adjustment weights for loss-functions. #msg = "Weight Adj. for Content: {0:.2e}, Style: {1:.2e}, Denoise: {2:.2e}" #print(msg.format(adj_content_val, adj_style_val, adj_denoise_val)) #msg = "Weight Adj. for Content: {0:.2e}, Denoise: {2:.2e}" #print(msg.format(adj_content_val, adj_denoise_val)) # Plot the content-, style- and mixed-images. plot_images(content_image=content_image, style_image=style_image, mixed_image=mixed_image) #Saving the mixed image after every 10 iterations filename='images/outputs_StyleTransfer/Mixed_Iteration' + str(i) +'.jpg' print(filename) save_image(mixed_image, filename) print() print("Final image:") plot_image_big(mixed_image) # Close the TensorFlow session to release its resources. session.close() # Return the mixed-image. return mixed_image """ Explanation: Loss Functions These helper-functions create the loss-functions that are used in optimization with TensorFlow. This function creates a TensorFlow operation for calculating the Mean Squared Error between the two input tensors. End of explanation """ content_filename = 'images/download.jpg' content_image = load_image(content_filename, max_size=None) filenamecontent='images/outputs_StyleTransfer/Content.jpg' print(filenamecontent) save_image(content_image, filenamecontent) """ Explanation: Example This example shows how to transfer the style of various images onto a portrait. First we load the content-image which has the overall contours that we want in the mixed-image. End of explanation """ style_filename = 'images/style4.jpg' style_image = load_image(style_filename, max_size=None) filenamestyle='images/outputs_StyleTransfer/Style.jpg' print(filenamestyle) save_image(style_image, filenamestyle) """ Explanation: Then we load the style-image which has the colours and textures we want in the mixed-image. End of explanation """ content_layer_ids = [4,6] """ Explanation: Then we define a list of integers which identify the layers in the neural network that we want to use for matching the content-image. These are indices into the layers in the neural network. For the VGG16 model, the 5th layer (index 4) seems to work well as the sole content-layer. End of explanation """ # The VGG16-model has 13 convolutional layers. # This selects all those layers as the style-layers. # This is somewhat slow to optimize. style_layer_ids = list(range(13)) # You can also select a sub-set of the layers, e.g. like this: # style_layer_ids = [1, 2, 3, 4] """ Explanation: Then we define another list of integers for the style-layers. End of explanation """ %%time img = style_transfer(content_image=content_image, style_image=style_image, content_layer_ids=content_layer_ids, style_layer_ids=style_layer_ids, weight_content=1.5, weight_style=10.0, weight_denoise=0.3, num_iterations=150, step_size=10.0) # Function for printing mixed output image filename='images/outputs_StyleTransfer/Mixed.jpg' save_image(img, filename) """ Explanation: Now perform the style-transfer. This automatically creates the appropriate loss-functions for the style- and content-layers, and then performs a number of optimization iterations. This will gradually create a mixed-image which has similar contours as the content-image, with the colours and textures being similar to the style-image. This can be very slow on a CPU! End of explanation """
rvuduc/cse6040-ipynbs
02--textproc.ipynb
bsd-3-clause
quote = """I wish you'd stop talking. I wish you'd stop prying and trying to find things out. I wish you were dead. No. That was silly and unkind. But I wish you'd stop talking.""" print (quote) def countWords1 (s): """Counts the number of words in a given input string.""" Lines = s.split ('\n') count = 0 for line in Lines: Words_in_line = line.split () count = count + len (Words_in_line) return count def countWords2 (s): """Counts the number of words in a given input string.""" return len (quote.split ()) count1 = countWords1 (quote) count2 = countWords2 (quote) print ("\nWord count: Method 1 says %d words, and Method 2 says %d." % (count1, count2)) assert count1 == count2 """ Explanation: CSE 6040, Fall 2015 [02]: Processing unstructured text Over the next two classes, we will build toward our first computational data mining problem, called the association rule mining problem. The basic task is to identify commonly co-occurring items in a series of transactions. We will apply this problem to a corpus of unstructured text. Consequently, this first class will introduce (or review, for some of you) a few essential useful Python tools for this problem: Strings Sets Dictionaries Regular expressions Files 0: Word count Given a fragment of text, represented by a string (possibly including newlines), how many words does it contain? Consider the following two methods to count words in a string. Look at these with a partner. End of explanation """ def yourCountWords (s): """Insert your method here.""" return 0 # Write some code to test your implementation here as well. """ Explanation: Q: Which would the two of you predict will be better, and why? (Insert your response to the above question(s) here.) Q: When might these methods not work as expected? With your partner, come up with one example input and write your own word counter, below, that handles that case. End of explanation """ Emails = ['quigbert@cc.gatech.edu', 'dummy@gatech.edu', 'dummy@vuduc.org', 'dummy@gatech.edu', 'hopeful@gatech.edu', 'overworked@gatech.edu', 'quigbert@cc.gatech.edu'] print (Emails) true_answer = 5 print ("\n'Emails' has %d unique addresses." % true_answer) """ Explanation: 1: Counting unique strings Suppose you are given a Python list of email addresses. Determine the number of unique addresses. End of explanation """ Dict = {} for email in Emails: Dict[email] = 1 count = len (Dict) assert count == true_answer print ("(Method 1 worked!)") """ Explanation: Method 1. Let's use a data structure called a dictionary, which stores (key, value) pairs. End of explanation """ UniqueEmails = set (Emails) count = len (UniqueEmails) assert count == true_answer print ("Method 2 worked!") """ Explanation: Method 2. Let's use a different data structure, called a set. It essentially implements a set in the mathematical sense. End of explanation """ import re # Loads the regular expression library p = re.compile ("impossible") m = p.search ("This mission is impossible.") if m == None: print ("Not found.") else: print ("Found pattern at position %d" % m.start ()) """ Explanation: Q: So, which method is better, and why? If you think one method is better than another for this problem, for what kinds of problems would you prefer the other method? (Insert your response to the above question(s) here.) 2: Regular expressions The preceding exercise hints at a general problem of finding specific patterns in text. A handy tool for this problem is Python's regular expression library. A regular expression is specially formatted pattern, written as a string. Matching patterns with regular expressions has 3 steps: You come up with a pattern to find You compile it into a pattern object You apply the pattern object to a string, to find instances of the pattern within the string It is easiest to see by example. What follows is just a small sample of what is possible with regular expressions in Python; refer to the regular expression documentation for many more examples and details. Example 1. The simplest pattern is text that you wish to match exactly. For instance, suppose you wish to find an instance of the word "impossible" in a piece of text. Here is a snippet of Python code to do it. Run this snippet. Try changing the search string and see what happens. End of explanation """ def findPhone1 (s): """Returns the first instance of a phone number in 's', or 'None'.""" phonePattern = re.compile ("\(\d\d\d\) \d\d\d-\d\d\d\d") hasPhone = phonePattern.search (s) if hasPhone: a = hasPhone.start () b = hasPhone.end () phone = s[a:b] else: phone = None return phone message = "Hi Betty. Give me a ring at (404) 555-1212 when you get a chance." findPhone1 (message) """ Explanation: The variable m in the example contains a match object if the pattern is found. You can perform queries against the match object, such as the one illustrated above. Beyond exact text, there is a rich syntax for specifying complex patterns. For instance, you can use character classes to match both "Impossible" and "impossible" using the pattern, "[Ii]mpossible". That is, the characters in square brackets represent the set of all characters that may match at the given position. As another example, you could match any digit using the character class, "[0123456789]", or the more compact range notation, "[0-9]". Thus, the pattern, "cat[xyz][0-9]hole" would match "catx3hole" but neither "catX3hole" nor "catxzhole". You can also match the complement of a character class set using a caret, "^", just after the opening square bracket. For instance, "cat[a-z][^0-9]hole" would match "catx@hole" but not "catx3hole". There are some common character classes, which have additional shortcuts. For instance, the special escaped d, or \d, will match any digit. So, to match a 7-digit phone number, you might use the pattern, "\d\d\d-\d\d\d\d". Parentheses actually have a special meaning in a regular expression pattern. Therefore, to match an exact parenthesis, you need to prefix it (or escape it) with a backslash, \. Example 2. For instance, suppose you wish to match a phone number written in the US standard format, like "(404) 555-1212". The pattern is a 3-digit area code, surrounded by parentheses, followed by a space, followed by a 7-digit number separated between the third and fourth digits. This pattern can be encoded as the following regular expression pattern: \(\d\d\d\) \d\d\d-\d\d\d\d Try the following example, which demonstrates the phone number matching pattern. End of explanation """ def findPhone2 (s): """Returns the first instance of a phone number in 's', or 'None'.""" phonePattern = re.compile ("\(\d\d\d\) *\d\d\d-\d\d\d\d") hasPhone = phonePattern.search (s) if hasPhone: a = hasPhone.start () b = hasPhone.end () phone = s[a:b] else: phone = None return phone findPhone2 ("Phone: (404)555-1212") """ Explanation: Example 4. You can make the phone number pattern more robust by allowing zero or more spaces between the area code and the phone number, using the * option: End of explanation """ fixFinder = re.compile ("(pre|suf)fix") assert fixFinder.search ("prefix") assert fixFinder.search ("suffix") assert not fixFinder.search ("infix") """ Explanation: Beyond "*", other wildcards include "+" to match one or more, as well as "?" to match zero or one instances. Example 5. It's also possible to match alternatives, using the or symbol, |. For instance, suppose you wish to recognize either of the words, "prefix" or "suffix": End of explanation """ def yourPhoneFinder (s): """Returns the first instance of a phone number in 's', or 'None'.""" # Fix the pattern: phonePattern = re.compile ("\(\d\d\d\) *\d\d\d-\d\d\d\d") hasPhone = phonePattern.search (s) if hasPhone: a = hasPhone.start () b = hasPhone.end () phone = s[a:b] else: phone = None return phone assert yourPhoneFinder ("(404)555-1212") assert yourPhoneFinder ("(404) 555-1212") assert yourPhoneFinder ("404-555-1212") assert yourPhoneFinder ("4045551212") """ Explanation: Q: Apply these technique to our phone number finder. Define a function that can match phone numbers in any of the following forms: (404) 555-1212 404-555-1212 404-5551212 404555-1212 4045551212 End of explanation """ def findPhone3 (s): """Returns a the first instance of a phone number in 's', or 'None'.""" phonePattern = re.compile ("\((?P<areacode>\d\d\d)\) (?P<number>\d\d\d-\d\d\d\d)") hasPhone = phonePattern.search (s) if hasPhone: areacode = hasPhone.group ('areacode') number = hasPhone.group ('number') phone = [areacode, number] else: phone = None return phone findPhone3 (message) """ Explanation: Example 6. Another common use-case is matching a string but extracting just a portion of it. For this purpose, you can use groups. Consider the simple form of phone numbers, such as "(404) 555-1212". Suppose you wish to match a phone number, but then extract just the digits of the area code from the remainder of the number. For instance, for the above you might produce the list, ['404','555-1212']. You can identify a group inside the pattern by enclosing the subpattern within parentheses, and then using a special syntax to give it a name. The name allows you to refer to the matched substring later on: End of explanation """ def findPhone4 (s): """Returns a the first instance of a phone number in 's', or 'None'.""" phonePattern = re.compile (r""" # Area code: \( (?P<areacode>\d\d\d) \) # Optional separator (one or more spaces) \s* # Phone number (?P<number>\d\d\d-\d\d\d\d) """, re.VERBOSE) hasPhone = phonePattern.search (s) if hasPhone: areacode = hasPhone.group ('areacode') number = hasPhone.group ('number') phone = [areacode, number] else: phone = None return phone findPhone4 (message) """ Explanation: In the preceding example, the syntax, (?P&lt;name&gt;xxx) defines a group named name for the subpattern represented abstractly by xxx. The example calls the match object's method, group("name"), to extract the matching substring. Example 7. One pitfall with regular expression patterns is that they get messy quickly. The re.compile() function takes a special flag, re.VERBOSE, which allows you to write regular expressions in a more structured and hopefully also more readable way. In particular, you can insert arbitrary amounts of whitespace as well as comments. End of explanation """ inbox = open ('skilling-j.inbox', 'r') # 'r' = read mode; use 'w' for writing assert inbox # Makes sure it opened OK all_messages = inbox.read () inbox.close () # Should close a file when you are done # Print first 500 characters print all_messages[0:500] """ Explanation: 3: File I/O Reading from or writing to a file is accomplished through a file object. In this example, the file "skilling-j.inbox" is a text file containing a bunch of email messages. You should download it if you haven't done so already: [download]. (If you are pulling directly from the class notebooks Github repo, this file is included already.) Example 1. You can read the entire file into a string by using open() to create a file object, and then reading its contents: End of explanation """ inbox = open ('skilling-j.inbox', 'r') # 'r' = read mode; use 'w' for writing assert inbox # Makes sure it opened OK count = 0 for line in inbox: # reads one line at a time count = count + 1 inbox.close () print ("The file has %d lines." % count) """ Explanation: Q: Do you anticipate any pitfalls in this approach? (Insert your response to the above question(s) here.) Example 2. A more memory-efficient way to read a file is to read chunks at a time. For text files, a particularly convenient way is to read the file one line at a time, using a file object's readline () method, or by looping directly over the object. The following example does so in order to count the number of lines in the file. End of explanation """
rasbt/pattern_classification
data_collecting/twitter_wordcloud.ipynb
gpl-3.0
%load_ext watermark %watermark -d -v -m -p twitter,pyprind,wordcloud,pandas,scipy,matplotlib """ Explanation: <br> <br> Turn Your Twitter Timeline into a Word Cloud Using Python <br> <br> Sections Requirements A. Downloading Your Twitter Timeline Tweets B. Creating the Word Cloud <br> <br> Requirements [back to top] Before we get started, I want to list some of the required packages to make this work! Below, you find a list of the basic packages which can be installed via pip install &lt;package_name&gt; twitter pyprind numpy matplotlib pandas scipy And the Python (2.7) wordcloud package by Andreas Mueller can be installed via pip install git+git://github.com/amueller/word_cloud.git Note that wordcloud requires Python's imaging library PIL. Depending on the operating system, the installation and setup of PIL can be quite challenging; however, when I tried to install it on different MacOS and Linux systems via conda it always seemed to work seamlessly: conda install pil Let me use my handy watermark extension to summarize the different packages and version numbers that were used in my case to download the twitter timeline and create the word cloud: End of explanation """ CONSUMER_KEY = 'enter your information here' CONSUMER_SECRET = 'enter your information here' ACCESS_TOKEN = 'enter your information here' ACCESS_TOKEN_SECRET = 'enter your information here' USER_NAME = 'enter your twitter handle here' """ Explanation: <br> <br> A. Downloading Your Twitter Timeline Tweets [back to top] In order to get access to the Twitter API through OAuth (open standard for authorization), we have to obtain our consumer information and access tokens first by registering our app on https://apps.twitter.com. End of explanation """ # Sebastian Raschka, 2014 # Code for downloading your personal twitter timeline. import twitter from datetime import datetime import time import re import sys import pandas as pd import pyprind as pp class TimelineMiner(object): def __init__(self, access_token, access_secret, consumer_key, consumer_secret, user_name): self.access_token = access_token self.access_secret = access_secret self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.user_name = user_name self.auth = None self.df = pd.DataFrame(columns=['timestamp', 'tweet'], dtype='str') def authenticate(self): self.auth = twitter.Twitter(auth=twitter.OAuth(self.access_token, self.access_secret, self.consumer_key, self.consumer_secret)) return bool(isinstance(self.auth, twitter.api.Twitter)) def get_timeline(self, max=0, keywords=[]): if keywords: self.df['keywords'] = '' tweet_ids = [self.auth.statuses.user_timeline( user_id=self.user_name, count=1 )[0]['id']] # the ID of my last tweet last_count = 200 counter = 0 while last_count == 200: timeline = self.auth.statuses.user_timeline(user_id=self.user_name, count=200, max_id=tweet_ids[-1]) for tweet in range(len(timeline)): text = timeline[tweet]['text'].replace('"', '\'') tweet_id = int(timeline[tweet]['id']) date = self.__get_date(timeline, tweet) if keywords: for k in keywords: if self.__check_keyword(text,k): self.df.loc[counter,'tweet'] = text self.df.loc[counter,'timestamp'] = date try: self.df.loc[counter,'keywords'].append(k) except AttributeError: self.df.loc[counter,'keywords'] = [k] try: self.df.loc[counter,'keywords'] = ';'.join(self.df.loc[counter,'keywords']) except KeyError: pass else: self.df.loc[counter,'tweet'] = text self.df.loc[counter,'timestamp'] = date counter += 1 if max and counter >= max: break sys.stdout.flush() sys.stdout.write('\rTweets downloaded: %s' %counter) if max and counter >= max: break last_count = len(timeline) tweet_ids.append(timeline[-1]['id']) time.sleep(1) print() def make_csv(self, path): self.df.to_csv(path, encoding='utf8') def __get_date(self, timeline, tweet): timest = datetime.strptime(timeline[tweet]['created_at'], "%a %b %d %H:%M:%S +0000 %Y") date = timest.strftime("%Y-%d-%m %H:%M:%S") return date def __check_keyword(self, s, key): return bool(re.search(key, s, re.IGNORECASE)) tm = twitter_timeline.TimelineMiner(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET, USER_NAME) print('Authentification successful: %s' %tm.authenticate()) tm.get_timeline(max=2000, keywords=[]) tm.df.head() """ Explanation: The following code can then be used to download your timeline "sequentially" in chunks of 200 tweets per request to overcome the twitter API limitation, which only allows you to download 200 tweets at a time. End of explanation """ %matplotlib inline import matplotlib.pyplot as plt from wordcloud import WordCloud, STOPWORDS # join tweets to a single string words = ' '.join(tm.df['tweet']) # remove URLs, RTs, and twitter handles no_urls_no_tags = " ".join([word for word in words.split() if 'http' not in word and not word.startswith('@') and word != 'RT' ]) wordcloud = WordCloud( font_path='/Users/sebastian/Library/Fonts/CabinSketch-Bold.ttf', stopwords=STOPWORDS, background_color='black', width=1800, height=1400 ).generate(no_urls_no_tags) plt.imshow(wordcloud) plt.axis('off') plt.savefig('./my_twitter_wordcloud_1.png', dpi=300) plt.show() """ Explanation: If the twitter_timeline.py script was executed terminal, you can read the "tweets" from the CSV file via import pandas as pd df = pd.read_csv('path/to/CSV') <br> <br> B. Creating the Word Cloud [back to top] Now that we collected the tweets from our twitter timeline the creation of the word cloud is pretty simple and straightforward thanks to the nice wordcloud module. End of explanation """ from scipy.misc import imread twitter_mask = imread('./twitter_mask.png', flatten=True) wordcloud = WordCloud( font_path='/Users/sebastian/Library/Fonts/CabinSketch-Bold.ttf', stopwords=STOPWORDS, background_color='white', width=1800, height=1400, mask=twitter_mask ).generate(no_urls_no_tags) plt.imshow(wordcloud) plt.axis("off") plt.savefig('./my_twitter_wordcloud_2.png', dpi=300) plt.show() """ Explanation: Surprise, surprise: The most common term I used in my tweets is obviously "Python!" <br> <br> To make the word cloud even more visually appealing, let us as a custom shape in form of the twitter logo: End of explanation """
GoogleCloudPlatform/ai-notebooks-extended
dataproc-hub-example/build/infrastructure-builder/mig/files/gcs_working_folder/examples/Python/storage/Cloud Storage client library.ipynb
apache-2.0
from google.cloud import storage """ Explanation: Cloud Storage client library This tutorial shows how to get started with the Cloud Storage Python client library. Create a storage bucket Buckets are the basic containers that hold your data. Everything that you store in Cloud Storage must be contained in a bucket. You can use buckets to organize your data and control access to your data. Start by importing the library: End of explanation """ client = storage.Client() print("Client created using default project: {}".format(client.project)) """ Explanation: The storage.Client object uses your default project. Alternatively, you can specify a project in the Client constructor. For more information about how the default project is determined, see the google-auth documentation. Run the following to create a client with your default project: End of explanation """ # client = storage.Client(project='your-project-id') """ Explanation: To explicitly specify a project when constructing the client, set the project parameter: End of explanation """ # Replace the string below with a unique name for the new bucket bucket_name = "your-new-bucket" # Creates the new bucket bucket = client.create_bucket(bucket_name) print("Bucket {} created.".format(bucket.name)) """ Explanation: Finally, create a bucket with a globally unique name. For more information about naming buckets, see Bucket name requirements. End of explanation """ buckets = client.list_buckets() print("Buckets in {}:".format(client.project)) for item in buckets: print("\t" + item.name) """ Explanation: List buckets in a project End of explanation """ bucket = client.get_bucket(bucket_name) print("Bucket name: {}".format(bucket.name)) print("Bucket location: {}".format(bucket.location)) print("Bucket storage class: {}".format(bucket.storage_class)) """ Explanation: Get bucket metadata The next cell shows how to get information on metadata of your Cloud Storage buckets. To learn more about specific bucket properties, see Bucket locations and Storage classes. End of explanation """ blob_name = "us-states.txt" blob = bucket.blob(blob_name) source_file_name = "resources/us-states.txt" blob.upload_from_filename(source_file_name) print("File uploaded to {}.".format(bucket.name)) """ Explanation: Upload a local file to a bucket Objects are the individual pieces of data that you store in Cloud Storage. Objects are referred to as "blobs" in the Python client library. There is no limit on the number of objects that you can create in a bucket. An object's name is treated as a piece of object metadata in Cloud Storage. Object names can contain any combination of Unicode characters (UTF-8 encoded) and must be less than 1024 bytes in length. For more information, including how to rename an object, see the Object name requirements. End of explanation """ blobs = bucket.list_blobs() print("Blobs in {}:".format(bucket.name)) for item in blobs: print("\t" + item.name) """ Explanation: List blobs in a bucket End of explanation """ blob = bucket.get_blob(blob_name) print("Name: {}".format(blob.id)) print("Size: {} bytes".format(blob.size)) print("Content type: {}".format(blob.content_type)) print("Public URL: {}".format(blob.public_url)) """ Explanation: Get a blob and display metadata See documentation for more information about object metadata. End of explanation """ output_file_name = "resources/downloaded-us-states.txt" blob.download_to_filename(output_file_name) print("Downloaded blob {} to {}.".format(blob.name, output_file_name)) """ Explanation: Download a blob to a local directory End of explanation """ blob = client.get_bucket(bucket_name).get_blob(blob_name) blob.delete() print("Blob {} deleted.".format(blob.name)) """ Explanation: Cleaning up Delete a blob End of explanation """ bucket = client.get_bucket(bucket_name) bucket.delete() print("Bucket {} deleted.".format(bucket.name)) """ Explanation: Delete a bucket Note that the bucket must be empty before it can be deleted. End of explanation """
ozak/CompEcon
notebooks/ipympl.ipynb
gpl-3.0
# Enabling the `widget` backend. # This requires jupyter-matplotlib a.k.a. ipympl. # ipympl can be install via pip or conda. %matplotlib widget import matplotlib.pyplot as plt import numpy as np # Testing matplotlib interactions with a simple plot fig = plt.figure() plt.plot(np.sin(np.linspace(0, 20, 100))); # Always hide the toolbar fig.canvas.toolbar_visible = False # Put it back to its default fig.canvas.toolbar_visible = 'fade-in-fade-out' # Change the toolbar position fig.canvas.toolbar_position = 'top' # Hide the Figure name at the top of the figure fig.canvas.header_visible = False # Hide the footer fig.canvas.footer_visible = False # Disable the resizing feature fig.canvas.resizable = False # If true then scrolling while the mouse is over the canvas will not move the entire notebook fig.canvas.capture_scroll = True """ Explanation: The Matplotlib Jupyter Widget Backend Enabling interaction with matplotlib charts in the Jupyter notebook and JupyterLab https://github.com/matplotlib/ipympl End of explanation """ fig.canvas.toolbar_visible = True display(fig.canvas) """ Explanation: You can also call display on fig.canvas to display the interactive plot anywhere in the notebooke End of explanation """ display(fig) """ Explanation: Or you can display(fig) to embed the current plot as a png End of explanation """ from mpl_toolkits.mplot3d import axes3d fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Grab some test data. X, Y, Z = axes3d.get_test_data(0.05) # Plot a basic wireframe. ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10) plt.show() """ Explanation: 3D plotting End of explanation """ # A more complex example from the matplotlib gallery np.random.seed(0) n_bins = 10 x = np.random.randn(1000, 3) fig, axes = plt.subplots(nrows=2, ncols=2) ax0, ax1, ax2, ax3 = axes.flatten() colors = ['red', 'tan', 'lime'] ax0.hist(x, n_bins, density=1, histtype='bar', color=colors, label=colors) ax0.legend(prop={'size': 10}) ax0.set_title('bars with legend') ax1.hist(x, n_bins, density=1, histtype='bar', stacked=True) ax1.set_title('stacked bar') ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False) ax2.set_title('stack step (unfilled)') # Make a multiple-histogram of data-sets with different length. x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]] ax3.hist(x_multi, n_bins, histtype='bar') ax3.set_title('different sample sizes') fig.tight_layout() plt.show() fig.canvas.toolbar_position = 'right' fig.canvas.toolbar_visible = False """ Explanation: Subplots End of explanation """ import ipywidgets as widgets # ensure we are interactive mode # this is default but if this notebook is executed out of order it may have been turned off plt.ion() fig = plt.figure() ax = fig.gca() ax.imshow(Z) widgets.AppLayout( center=fig.canvas, footer=widgets.Button(icon='check'), pane_heights=[0, 6, 1] ) """ Explanation: Interactions with other widgets and layouting When you want to embed the figure into a layout of other widgets you should call plt.ioff() before creating the figure otherwise plt.figure() will trigger a display of the canvas automatically and outside of your layout. Without using ioff Here we will end up with the figure being displayed twice. The button won't do anything it just placed as an example of layouting. End of explanation """ plt.ioff() fig = plt.figure() plt.ion() ax = fig.gca() ax.imshow(Z) widgets.AppLayout( center=fig.canvas, footer=widgets.Button(icon='check'), pane_heights=[0, 6, 1] ) """ Explanation: Fixing the double display with ioff If we make sure interactive mode is off when we create the figure then the figure will only display where we want it to. There is ongoing work to allow usage of ioff as a context manager, see the ipympl issue and the matplotlib issue End of explanation """ # When using the `widget` backend from ipympl, # fig.canvas is a proper Jupyter interactive widget, which can be embedded in # an ipywidgets layout. See https://ipywidgets.readthedocs.io/en/stable/examples/Layout%20Templates.html # One can bound figure attributes to other widget values. from ipywidgets import AppLayout, FloatSlider plt.ioff() slider = FloatSlider( orientation='horizontal', description='Factor:', value=1.0, min=0.02, max=2.0 ) slider.layout.margin = '0px 30% 0px 30%' slider.layout.width = '40%' fig = plt.figure() fig.canvas.header_visible = False fig.canvas.layout.min_height = '400px' plt.title('Plotting: y=sin({} * x)'.format(slider.value)) x = np.linspace(0, 20, 500) lines = plt.plot(x, np.sin(slider.value * x)) def update_lines(change): plt.title('Plotting: y=sin({} * x)'.format(change.new)) lines[0].set_data(x, np.sin(change.new * x)) fig.canvas.draw() fig.canvas.flush_events() slider.observe(update_lines, names='value') AppLayout( center=fig.canvas, footer=slider, pane_heights=[0, 6, 1] ) """ Explanation: Interacting with other widgets Changing a line plot with a slide End of explanation """ # precomputing all images x = np.linspace(0,np.pi,200) y = np.linspace(0,10,200) X,Y = np.meshgrid(x,y) parameter = np.linspace(-5,5) example_image_stack = np.sin(X)[None,:,:]+np.exp(np.cos(Y[None,:,:]*parameter[:,None,None])) plt.ioff() fig = plt.figure() plt.ion() im = plt.imshow(example_image_stack[0]) def update(change): im.set_data(example_image_stack[change['new']]) fig.canvas.draw_idle() slider = widgets.IntSlider(value=0, min=0, max=len(parameter)-1) slider.observe(update, names='value') widgets.VBox([slider, fig.canvas]) """ Explanation: Update image data in a performant manner Two useful tricks to improve performance when updating an image displayed with matplolib are to: 1. Use the set_data method instead of calling imshow 2. Precompute and then index the array End of explanation """ plt.ioff() fig = plt.figure() plt.ion() im = plt.imshow(example_image_stack[0]) out = widgets.Output() @out.capture() def update(change): with out: if change['name'] == 'value': im.set_data(example_image_stack[change['new']]) fig.canvas.draw_idle slider = widgets.IntSlider(value=0, min=0, max=len(parameter)+10) slider.observe(update) display(widgets.VBox([slider, fig.canvas])) display(out) """ Explanation: Debugging widget updates and matplotlib callbacks If an error is raised in the update function then will not always display in the notebook which can make debugging difficult. This same issue is also true for matplotlib callbacks on user events such as mousemovement, for example see issue. There are two ways to see the output: 1. In jupyterlab the output will show up in the Log Console (View > Show Log Console) 2. using ipywidgets.Output Here is an example of using an Output to capture errors in the update function from the previous example. To induce errors we changed the slider limits so that out of bounds errors will occur: From: slider = widgets.IntSlider(value=0, min=0, max=len(parameter)-1) To: slider = widgets.IntSlider(value=0, min=0, max=len(parameter)+10) If you move the slider all the way to the right you should see errors from the Output widget End of explanation """
root-mirror/training
INSIGHTS2018/Exercises/WorkingWithFiles/WritingOnFilesExercise.ipynb
gpl-2.0
import ROOT """ Explanation: Writing on files This is a Python notebook in which you will practice the concepts learned during the lectures. Startup ROOT Import the ROOT module: this will activate the integration layer with the notebook automatically End of explanation """ rndm = ROOT.TRandom3(1) filename = "histos.root" # Here open a file and create three histograms for i in xrange(1024): # Use the following lines to feed the Fill method of the histograms in order to fill rndm.Gaus() rndm.Exp(1) rndm.Uniform(-4,4) # Here write the three histograms on the file and close the file """ Explanation: Writing histograms Create a TFile containing three histograms filled with random numbers distributed according to a Gaus, an exponential and a uniform distribution. Close the file: you will reopen it later. End of explanation """ ! ls . ! echo Now listing the content of the file ! rootls -l #filename here """ Explanation: Now, you can invoke the ls command from within the notebook to list the files in this directory. Check that the file is there. You can invoke the rootls command to see what's inside the file. End of explanation """ %jsroot on f = ROOT.TFile(filename) c = ROOT.TCanvas() c.Divide(2,2) c.cd(1) f.gaus.Draw() # finish the drawing in each pad # Draw the Canvas """ Explanation: Access the histograms and draw them in Python. Remember that you need to create a TCanvas before and draw it too in order to inline the plots in the notebooks. You can switch to the interactive JavaScript visualisation using the %jsroot on "magic" command. End of explanation """ %cpp TFile f("histos.root"); TH1F *hg, *he, *hu; f.GetObject("gaus", hg); // ... read the histograms and draw them in each pad """ Explanation: You can now repeat the exercise above using C++. Transform the cell in a C++ cell using the %%cpp "magic". End of explanation """ f = ROOT.TXMLFile("histos.xml","RECREATE") hg = ROOT.TH1F("gaus","Gaussian numbers", 64, -4, 4) he = ROOT.TH1F("expo","Exponential numbers", 64, -4, 4) hu = ROOT.TH1F("unif","Uniform numbers", 64, -4, 4) for i in xrange(1024): hg.Fill(rndm.Gaus()) # ... Same as above! ! ls -l histos.xml histos.root ! cat histos.xml """ Explanation: Inspect the content of the file: TXMLFile ROOT provides a different kind of TFile, TXMLFile. It has the same interface and it's very useful to better understand how objects are written in files by ROOT. Repeat the exercise above, either on Python or C++ - your choice, using a TXMLFILE rather than a TFile and then display its content with the cat command. Can you see how the content of the individual bins of the histograms is stored? And the colour of its markers? Do you understand why the xml file is bigger than the root one even if they have the same content? End of explanation """
dr-nate/msmbuilder
examples/tICA-vs-PCA.ipynb
lgpl-2.1
%matplotlib inline import numpy as np from matplotlib import pyplot as plt xx, yy = np.meshgrid(np.linspace(-2,2), np.linspace(-3,3)) zz = 0 # We can only visualize so many dimensions ww = 5 * (xx-1)**2 * (xx+1)**2 + yy**2 + zz**2 c = plt.contourf(xx, yy, ww, np.linspace(-1, 15, 20), cmap='viridis_r') plt.contour(xx, yy, ww, np.linspace(-1, 15, 20), cmap='Greys') plt.xlabel('$x$', fontsize=18) plt.ylabel('$y$', fontsize=18) plt.colorbar(c, label='$E(x, y, z=0)$') plt.tight_layout() import simtk.openmm as mm def propagate(n_steps=10000): system = mm.System() system.addParticle(1) force = mm.CustomExternalForce('5*(x-1)^2*(x+1)^2 + y^2 + z^2') force.addParticle(0, []) system.addForce(force) integrator = mm.LangevinIntegrator(500, 1, 0.02) context = mm.Context(system, integrator) context.setPositions([[0, 0, 0]]) context.setVelocitiesToTemperature(500) x = np.zeros((n_steps, 3)) for i in range(n_steps): x[i] = (context.getState(getPositions=True) .getPositions(asNumpy=True) ._value) integrator.step(1) return x """ Explanation: tICA vs. PCA This example uses OpenMM to generate example data to compare two methods for dimensionality reduction: tICA and PCA. Define dynamics First, let's use OpenMM to run some dynamics on the 3D potential energy function $$E(x,y,z) = 5 \cdot (x-1)^2 \cdot (x+1)^2 + y^2 + z^2$$ From looking at this equation, we can see that along the x dimension, the potential is a double-well, whereas along the y and z dimensions, we've just got a harmonic potential. So, we should expect that x is the slow degree of freedom, whereas the system should equilibrate rapidly along y and z. End of explanation """ trajectory = propagate(10000) ylabels = ['x', 'y', 'z'] for i in range(3): plt.subplot(3, 1, i+1) plt.plot(trajectory[:, i]) plt.ylabel(ylabels[i]) plt.xlabel('Simulation time') plt.tight_layout() """ Explanation: Run Dynamics Okay, let's run the dynamics. The first plot below shows the x, y and z coordinate vs. time for the trajectory, and the second plot shows each of the 1D and 2D marginal distributions. End of explanation """ from msmbuilder.decomposition import tICA, PCA tica = tICA(n_components=1, lag_time=100) pca = PCA(n_components=1) tica.fit([trajectory]) pca.fit([trajectory]) """ Explanation: Note that the variance of x is much lower than the variance in y or z, despite its bi-modal distribution. Fit tICA and PCA models End of explanation """ plt.subplot(1,2,1) plt.title('1st tIC') plt.bar([1,2,3], tica.components_[0], color='b') plt.xticks([1.5,2.5,3.5], ['x', 'y', 'z']) plt.subplot(1,2,2) plt.title('1st PC') plt.bar([1,2,3], pca.components_[0], color='r') plt.xticks([1.5,2.5,3.5], ['x', 'y', 'z']) plt.show() print('1st tIC', tica.components_ / np.linalg.norm(tica.components_)) print('1st PC ', pca.components_ / np.linalg.norm(pca.components_)) """ Explanation: See what they find End of explanation """ c = plt.contourf(xx, yy, ww, np.linspace(-1, 15, 20), cmap='viridis_r') plt.contour(xx, yy, ww, np.linspace(-1, 15, 20), cmap='Greys') plt.plot([0, tica.components_[0, 0]], [0, tica.components_[0, 1]], lw=5, color='b', label='tICA') plt.plot([0, pca.components_[0, 0]], [0, pca.components_[0, 1]], lw=5, color='r', label='PCA') plt.xlabel('$x$', fontsize=18) plt.ylabel('$y$', fontsize=18) plt.legend(loc='best') plt.tight_layout() """ Explanation: Note that the first tIC "finds" a projection that just resolves the x coordinate, whereas PCA doesn't. End of explanation """
JohnCrickett/PythonExamples
Enums.ipynb
mit
from enum import Enum class MyEnum(Enum): first = 1 second = 2 third = 3 """ Explanation: Enums This notebook is an introduction to Python Enums as introduced in Python 3.4 and subsequently backported to other version of Python. More details can be found in the library documentation: https://docs.python.org/3.4/library/enum.html Enumerations are sets of symbolic names bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over. A simple example is: python from enum import Enum class Color(Enum): red = 1 green = 2 blue = 3 Let's walk through the example above. First you import the Enum library with the line: python from enum import Enum Then you subclass Enum to create your own enumerated class with the values listed within the class: python class Color(Enum): red = 1 green = 2 blue = 3 Try it below, create your own Enum. End of explanation """ print(MyEnum.first) print(repr(MyEnum.first)) """ Explanation: Nomenclature Python has a specific nomenclature for enums. The class Color is an enumeration (or enum) The attributes Color.red, Color.green, etc., are enumeration members (or enum members). The enum members have names and values (the name of Color.red is red, the value of Color.blue is 3, etc.) Printing and Representing Enums Enum types have human readable string representations for print and repr: End of explanation """ type(MyEnum.first) """ Explanation: The type of an enumeration member is the enumeration it belongs to: End of explanation """ SecondEnum = Enum('SecondEnum', 'first, second, third') print(SecondEnum.first) """ Explanation: Alternative way to create an Enum There is an alternative way to create and Enum, that matches Python's NamedTuple: python Colour = Enum('Colour', 'red, green') Try it below: End of explanation """
tarashor/vibrations
py/notebooks/MatricesForOrthogonalCoordinates.ipynb
mit
from sympy import * from geom_util import * from sympy.vector import CoordSys3D N = CoordSys3D('N') alpha1, alpha2, alpha3 = symbols("alpha_1 alpha_2 alpha_3", real = True, positive=True) init_printing() %matplotlib inline %reload_ext autoreload %autoreload 2 %aimport geom_util """ Explanation: Matrix generation Init symbols for sympy End of explanation """ # h1 = Function("H1") # h2 = Function("H2") # h3 = Function("H3") # H1 = h1(alpha1, alpha2, alpha3) # H2 = h2(alpha1, alpha2, alpha3) # H3 = h3(alpha1, alpha2, alpha3) H1,H2,H3=symbols('H1,H2,H3') H=[H1, H2, H3] DIM=3 dH = zeros(DIM,DIM) for i in range(DIM): for j in range(DIM): dH[i,j]=Symbol('H_{{{},{}}}'.format(i+1,j+1)) dH """ Explanation: Lame params End of explanation """ G_up = getMetricTensorUpLame(H1, H2, H3) """ Explanation: Metric tensor ${\displaystyle \hat{G}=\sum_{i,j} g^{ij}\vec{R}_i\vec{R}_j}$ End of explanation """ G_down = getMetricTensorDownLame(H1, H2, H3) """ Explanation: ${\displaystyle \hat{G}=\sum_{i,j} g_{ij}\vec{R}^i\vec{R}^j}$ End of explanation """ DIM=3 G_down_diff = MutableDenseNDimArray.zeros(DIM, DIM, DIM) for i in range(DIM): for j in range(DIM): for k in range(DIM): G_down_diff[i,i,k]=2*H[i]*dH[i,k] GK = getChristoffelSymbols2(G_up, G_down_diff, (alpha1, alpha2, alpha3)) GK """ Explanation: Christoffel symbols End of explanation """ def row_index_to_i_j_grad(i_row): return i_row // 3, i_row % 3 B = zeros(9, 12) B[0,1] = S(1) B[1,2] = S(1) B[2,3] = S(1) B[3,5] = S(1) B[4,6] = S(1) B[5,7] = S(1) B[6,9] = S(1) B[7,10] = S(1) B[8,11] = S(1) for row_index in range(9): i,j=row_index_to_i_j_grad(row_index) B[row_index, 0] = -GK[i,j,0] B[row_index, 4] = -GK[i,j,1] B[row_index, 8] = -GK[i,j,2] B """ Explanation: Gradient of vector $ \left( \begin{array}{c} \nabla_1 u_1 \ \nabla_2 u_1 \ \nabla_3 u_1 \ \nabla_1 u_2 \ \nabla_2 u_2 \ \nabla_3 u_2 \ \nabla_1 u_3 \ \nabla_2 u_3 \ \nabla_3 u_3 \ \end{array} \right) = B \cdot \left( \begin{array}{c} u_1 \ \frac { \partial u_1 } { \partial \alpha_1} \ \frac { \partial u_1 } { \partial \alpha_2} \ \frac { \partial u_1 } { \partial \alpha_3} \ u_2 \ \frac { \partial u_2 } { \partial \alpha_1} \ \frac { \partial u_2 } { \partial \alpha_2} \ \frac { \partial u_2 } { \partial \alpha_3} \ u_3 \ \frac { \partial u_3 } { \partial \alpha_1} \ \frac { \partial u_3 } { \partial \alpha_2} \ \frac { \partial u_3 } { \partial \alpha_3} \ \end{array} \right) = B \cdot D \cdot \left( \begin{array}{c} u^1 \ \frac { \partial u^1 } { \partial \alpha_1} \ \frac { \partial u^1 } { \partial \alpha_2} \ \frac { \partial u^1 } { \partial \alpha_3} \ u^2 \ \frac { \partial u^2 } { \partial \alpha_1} \ \frac { \partial u^2 } { \partial \alpha_2} \ \frac { \partial u^2 } { \partial \alpha_3} \ u^3 \ \frac { \partial u^3 } { \partial \alpha_1} \ \frac { \partial u^3 } { \partial \alpha_2} \ \frac { \partial u^3 } { \partial \alpha_3} \ \end{array} \right) $ End of explanation """ E=zeros(6,9) E[0,0]=1 E[1,4]=1 E[2,8]=1 E[3,1]=1 E[3,3]=1 E[4,2]=1 E[4,6]=1 E[5,5]=1 E[5,7]=1 E def E_NonLinear(grad_u): N = 3 du = zeros(N, N) # print("===Deformations===") for i in range(N): for j in range(N): index = i*N+j du[j,i] = grad_u[index] # print("========") I = eye(3) a_values = S(1)/S(2) * du * G_up E_NL = zeros(6,9) E_NL[0,0] = a_values[0,0] E_NL[0,3] = a_values[0,1] E_NL[0,6] = a_values[0,2] E_NL[1,1] = a_values[1,0] E_NL[1,4] = a_values[1,1] E_NL[1,7] = a_values[1,2] E_NL[2,2] = a_values[2,0] E_NL[2,5] = a_values[2,1] E_NL[2,8] = a_values[2,2] E_NL[3,1] = 2*a_values[0,0] E_NL[3,4] = 2*a_values[0,1] E_NL[3,7] = 2*a_values[0,2] E_NL[4,0] = 2*a_values[2,0] E_NL[4,3] = 2*a_values[2,1] E_NL[4,6] = 2*a_values[2,2] E_NL[5,2] = 2*a_values[1,0] E_NL[5,5] = 2*a_values[1,1] E_NL[5,8] = 2*a_values[1,2] return E_NL %aimport geom_util u=getUHat3D(alpha1, alpha2, alpha3) # u=getUHatU3Main(alpha1, alpha2, alpha3) gradu=B*u E_NL = E_NonLinear(gradu)*B E_NL """ Explanation: Strain tensor $ \left( \begin{array}{c} \varepsilon_{11} \ \varepsilon_{22} \ \varepsilon_{33} \ 2\varepsilon_{12} \ 2\varepsilon_{13} \ 2\varepsilon_{23} \ \end{array} \right) = \left(E + E_{NL} \left( \nabla \vec{u} \right) \right) \cdot \left( \begin{array}{c} \nabla_1 u_1 \ \nabla_2 u_1 \ \nabla_3 u_1 \ \nabla_1 u_2 \ \nabla_2 u_2 \ \nabla_3 u_2 \ \nabla_1 u_3 \ \nabla_2 u_3 \ \nabla_3 u_3 \ \end{array} \right)$ End of explanation """ P=zeros(12,12) P[0,0]=H[0] P[1,0]=dH[0,0] P[1,1]=H[0] P[2,0]=dH[0,1] P[2,2]=H[0] P[3,0]=dH[0,2] P[3,3]=H[0] P[4,4]=H[1] P[5,4]=dH[1,0] P[5,5]=H[1] P[6,4]=dH[1,1] P[6,6]=H[1] P[7,4]=dH[1,2] P[7,7]=H[1] P[8,8]=H[2] P[9,8]=dH[2,0] P[9,9]=H[2] P[10,8]=dH[2,1] P[10,10]=H[2] P[11,8]=dH[2,2] P[11,11]=H[2] P=simplify(P) P B_P = zeros(9,9) for i in range(3): for j in range(3): row_index = i*3+j B_P[row_index, row_index] = 1/(H[i]*H[j]) Grad_U_P = simplify(B_P*B*P) Grad_U_P StrainL=simplify(E*Grad_U_P) StrainL %aimport geom_util u=getUHat3D(alpha1, alpha2, alpha3) gradup=Grad_U_P*u E_NLp = E_NonLinear(gradup)*Grad_U_P simplify(E_NLp) """ Explanation: Physical coordinates $u_i=u_{[i]} H_i$ End of explanation """ T=zeros(12,6) T[0,0]=1 T[0,2]=alpha3 T[1,1]=1 T[1,3]=alpha3 T[3,2]=1 T[8,4]=1 T[9,5]=1 T D_p_T = StrainL*T simplify(D_p_T) u = Function("u") t = Function("theta") w = Function("w") u1=u(alpha1)+alpha3*t(alpha1) u3=w(alpha1) gu = zeros(12,1) gu[0] = u1 gu[1] = u1.diff(alpha1) gu[3] = u1.diff(alpha3) gu[8] = u3 gu[9] = u3.diff(alpha1) gradup=Grad_U_P*gu # o20=(K*u(alpha1)-w(alpha1).diff(alpha1)+t(alpha1))/2 # o21=K*t(alpha1) # O=1/2*o20*o20+alpha3*o20*o21-alpha3*K/2*o20*o20 # O=expand(O) # O=collect(O,alpha3) # simplify(O) StrainNL = E_NonLinear(gradup)*gradup simplify(StrainNL) """ Explanation: Tymoshenko theory $u_1 \left( \alpha_1, \alpha_2, \alpha_3 \right)=u\left( \alpha_1 \right)+\alpha_3\gamma \left( \alpha_1 \right) $ $u_2 \left( \alpha_1, \alpha_2, \alpha_3 \right)=0 $ $u_3 \left( \alpha_1, \alpha_2, \alpha_3 \right)=w\left( \alpha_1 \right) $ $ \left( \begin{array}{c} u_1 \ \frac { \partial u_1 } { \partial \alpha_1} \ \frac { \partial u_1 } { \partial \alpha_2} \ \frac { \partial u_1 } { \partial \alpha_3} \ u_2 \ \frac { \partial u_2 } { \partial \alpha_1} \ \frac { \partial u_2 } { \partial \alpha_2} \ \frac { \partial u_2 } { \partial \alpha_3} \ u_3 \ \frac { \partial u_3 } { \partial \alpha_1} \ \frac { \partial u_3 } { \partial \alpha_2} \ \frac { \partial u_3 } { \partial \alpha_3} \ \end{array} \right) = T \cdot \left( \begin{array}{c} u \ \frac { \partial u } { \partial \alpha_1} \ \gamma \ \frac { \partial \gamma } { \partial \alpha_1} \ w \ \frac { \partial w } { \partial \alpha_1} \ \end{array} \right) $ End of explanation """ L=zeros(12,12) h=Symbol('h') # p0=1/2-alpha3/h # p1=1/2+alpha3/h # p2=1-(2*alpha3/h)**2 P0=Function('p_0') P1=Function('p_1') P2=Function('p_2') # p1=1/2+alpha3/h # p2=1-(2*alpha3/h)**2 p0=P0(alpha3) p1=P1(alpha3) p2=P2(alpha3) L[0,0]=p0 L[0,2]=p1 L[0,4]=p2 L[1,1]=p0 L[1,3]=p1 L[1,5]=p2 L[3,0]=p0.diff(alpha3) L[3,2]=p1.diff(alpha3) L[3,4]=p2.diff(alpha3) L[8,6]=p0 L[8,8]=p1 L[8,10]=p2 L[9,7]=p0 L[9,9]=p1 L[9,11]=p2 L[11,6]=p0.diff(alpha3) L[11,8]=p1.diff(alpha3) L[11,10]=p2.diff(alpha3) L D_p_L = StrainL*L simplify(D_p_L) h = 0.5 exp=(0.5-alpha3/h)*(1-(2*alpha3/h)**2)#/(1+alpha3*0.8) p02=integrate(exp, (alpha3, -h/2, h/2)) integral = expand(simplify(p02)) integral """ Explanation: Square theory $u^1 \left( \alpha_1, \alpha_2, \alpha_3 \right)=u_{10}\left( \alpha_1 \right)p_0\left( \alpha_3 \right)+u_{11}\left( \alpha_1 \right)p_1\left( \alpha_3 \right)+u_{12}\left( \alpha_1 \right)p_2\left( \alpha_3 \right) $ $u^2 \left( \alpha_1, \alpha_2, \alpha_3 \right)=0 $ $u^3 \left( \alpha_1, \alpha_2, \alpha_3 \right)=u_{30}\left( \alpha_1 \right)p_0\left( \alpha_3 \right)+u_{31}\left( \alpha_1 \right)p_1\left( \alpha_3 \right)+u_{32}\left( \alpha_1 \right)p_2\left( \alpha_3 \right) $ $ \left( \begin{array}{c} u^1 \ \frac { \partial u^1 } { \partial \alpha_1} \ \frac { \partial u^1 } { \partial \alpha_2} \ \frac { \partial u^1 } { \partial \alpha_3} \ u^2 \ \frac { \partial u^2 } { \partial \alpha_1} \ \frac { \partial u^2 } { \partial \alpha_2} \ \frac { \partial u^2 } { \partial \alpha_3} \ u^3 \ \frac { \partial u^3 } { \partial \alpha_1} \ \frac { \partial u^3 } { \partial \alpha_2} \ \frac { \partial u^3 } { \partial \alpha_3} \ \end{array} \right) = L \cdot \left( \begin{array}{c} u_{10} \ \frac { \partial u_{10} } { \partial \alpha_1} \ u_{11} \ \frac { \partial u_{11} } { \partial \alpha_1} \ u_{12} \ \frac { \partial u_{12} } { \partial \alpha_1} \ u_{30} \ \frac { \partial u_{30} } { \partial \alpha_1} \ u_{31} \ \frac { \partial u_{31} } { \partial \alpha_1} \ u_{32} \ \frac { \partial u_{32} } { \partial \alpha_1} \ \end{array} \right) $ End of explanation """ rho=Symbol('rho') B_h=zeros(3,12) B_h[0,0]=1 B_h[1,4]=1 B_h[2,8]=1 M=simplify(rho*P.T*B_h.T*G_up*B_h*P) M """ Explanation: Mass matrix End of explanation """
tensorflow/tpu
tools/colab/regression_sine_data_with_keras.ipynb
apache-2.0
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ Explanation: <a href="https://colab.research.google.com/github/tensorflow/tpu/blob/0e3cfbdfbcf321681c1ac1c387baf7a1a41d8d21/tools/colab/regression_sine_data_with_keras.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ import math import os import matplotlib.pyplot as plt import numpy as np import tensorflow as tf print(tf.__version__) import distutils if distutils.version.LooseVersion(tf.__version__) < '2.0': raise Exception('This notebook is compatible with TensorFlow 2.0 or higher.') """ Explanation: A simple regression model using Keras with Cloud TPUs Overview This notebook demonstrates using Cloud TPUs in colab to build a simple regression model using y = sin(x) to predict y for given x. This model generates huge amounts of data that and demonstrates the training performance advantage of Cloud TPU. The model trains for 10 epochs with 512 steps per epoch on TPU and completes in approximately 2 minutes. This notebook is hosted on GitHub. To view it in its original repository, after opening the notebook, select File > View on GitHub. Learning objectives In this Colab, you will learn how to: * Create and compile a Keras model on TPU with a distribution strategy. * Train, evaluate, and and generate predictions on Cloud TPU. * Compare the performance of a TPU versus a CPU. Instructions <h3> &nbsp;&nbsp;Train on TPU&nbsp;&nbsp; <a href="https://cloud.google.com/tpu/"><img valign="middle" src="https://raw.githubusercontent.com/GoogleCloudPlatform/tensorflow-without-a-phd/master/tensorflow-rl-pong/images/tpu-hexagon.png" width="50"></a></h3> On the main menu, click Runtime and select Change runtime type. Set "TPU" as the hardware accelerator. Click Runtime again and select Runtime > Run All. You can also run the cells manually with Shift-ENTER. Imports End of explanation """ use_tpu = True #@param {type:"boolean"} if use_tpu: assert 'COLAB_TPU_ADDR' in os.environ, 'Missing TPU; did you request a TPU in Notebook Settings?' if 'COLAB_TPU_ADDR' in os.environ: TPU_ADDRESS = 'grpc://{}'.format(os.environ['COLAB_TPU_ADDR']) else: TPU_ADDRESS = '' resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu=TPU_ADDRESS) tf.config.experimental_connect_to_cluster(resolver) tf.tpu.experimental.initialize_tpu_system(resolver) print("All devices: ", tf.config.list_logical_devices('TPU')) """ Explanation: Resolve TPU Address End of explanation """ data_size = 2**18 x = np.linspace(0, 6, data_size, dtype=np.float32) np.random.shuffle(x) y = -20 * np.sin(x, dtype=np.float32) + 3 + np.random.normal(0, 1, (data_size,)).astype(np.float32) x = x.reshape(-1, 1) y = y.reshape(-1, 1) train_x, test_x = x[:data_size//2], x[data_size//2:] train_y, test_y = y[:data_size//2], y[data_size//2:] plt.plot(x, y, 'bo') """ Explanation: Creating data for y = sin(x). Sine wave data is created using numpy. And to make it more difficult, random noise is added to the sine wave. End of explanation """ def get_model(): return tf.keras.models.Sequential([ tf.keras.layers.Dense(1, input_shape=(1,)), tf.keras.layers.Dense(200, activation='sigmoid'), tf.keras.layers.Dense(80, activation='sigmoid'), tf.keras.layers.Dense(1) ]) """ Explanation: Define model: Model will have an input layer where it takes in the x coordinate, two densely connected layers with 200 and 80 nodes, and an output layer where it returns the predicted y value. End of explanation """ strategy = tf.distribute.experimental.TPUStrategy(resolver) with strategy.scope(): model = get_model() model.compile(optimizer=tf.keras.optimizers.SGD(.01), loss='mean_squared_error', metrics=['mean_squared_error']) """ Explanation: Compiling the model with a distribution strategy To make the model usable by a TPU, we first must create and compile it using a distribution strategy. End of explanation """ model.fit(train_x, train_y, epochs=10, steps_per_epoch=512) """ Explanation: Training of the model on TPU End of explanation """ predictions = model.predict(test_x) plt.plot(test_x, predictions, 'ro') """ Explanation: Prediction For predictions, same model weights are being used. End of explanation """
ethen8181/machine-learning
keras/nn_keras_basics.ipynb
mit
# code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(plot_style=False) os.chdir(path) # 1. magic to print version # 2. magic so that the notebook will reload external python modules %load_ext watermark %load_ext autoreload %autoreload 2 import numpy as np import pandas as pd from keras.datasets import mnist from keras.utils import np_utils from keras.optimizers import RMSprop from keras.models import Sequential, load_model from keras.layers.core import Dense, Dropout, Activation %watermark -a 'Ethen' -d -t -v -p numpy,pandas,keras """ Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Keras-Basics" data-toc-modified-id="Keras-Basics-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Keras Basics</a></span><ul class="toc-item"><li><span><a href="#Saving-and-loading-the-models" data-toc-modified-id="Saving-and-loading-the-models-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Saving and loading the models</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> End of explanation """ n_classes = 10 n_features = 784 # mnist is a 28 * 28 image # load the dataset and some preprocessing step that can be skipped (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, n_features) X_test = X_test.reshape(10000, n_features) X_train = X_train.astype('float32') X_test = X_test.astype('float32') # images takes values between 0 - 255, we can normalize it # by dividing every number by 255 X_train /= 255 X_test /= 255 print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices (one-hot encoding) # note: you HAVE to to this step Y_train = np_utils.to_categorical(y_train, n_classes) Y_test = np_utils.to_categorical(y_test , n_classes) """ Explanation: Keras Basics Basic Keras API to build a simple multi-layer neural network. End of explanation """ # define the model model = Sequential() model.add(Dense(512, input_dim = n_features)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(512)) model.add(Activation('relu')) model.add(Dropout(0.2)) model.add(Dense(n_classes)) model.add(Activation('softmax')) # we can check the summary to check the number of parameters model.summary() """ Explanation: Basics of training a model: The easiest way to build models in keras is to use Sequential model and the .add() method to stack layers together in sequence to build up our network. We start with Dense (fully-connected layers), where we specify how many nodes you wish to have for the layer. Since the first layer that we're going to add is the input layer, we have to make sure that the input_dim parameter matches the number of features (columns) in the training set. Then after the first layer, we don't need to specify the size of the input anymore. Then we specify the Activation function for that layer, and add a Dropout layer if we wish. For the last Dense and Activation layer we need to specify the number of class as the output and softmax to tell it to output the predicted class's probability. End of explanation """ model.compile(loss = 'categorical_crossentropy', optimizer = RMSprop(), metrics = ['accuracy']) n_epochs = 10 batch_size = 128 history = model.fit( X_train, Y_train, batch_size = batch_size, epochs = n_epochs, verbose = 1, # set it to 0 if we don't want to have progess bars validation_data = (X_test, Y_test) ) # history attribute stores the training and validation score and loss history.history # .evaluate gives the loss and metric evaluation score for the dataset, # here the result matches the validation set's history above print('metrics: ', model.metrics_names) score = model.evaluate(X_test, Y_test, verbose = 0) score # stores the weight of the model, # it's a list, note that the length is 6 because we have 3 dense layer # and each one has it's associated bias term weights = model.get_weights() print(len(weights)) # W1 should have 784, 512 for the 784 # feauture column and the 512 the number # of dense nodes that we've specified W1, b1, W2, b2, W3, b3 = weights print(W1.shape) print(b1.shape) # predict the accuracy y_pred = model.predict_classes(X_test, verbose = 0) accuracy = np.sum(y_test == y_pred) / X_test.shape[0] print('valid accuracy: %.2f' % (accuracy * 100)) """ Explanation: Once our model looks good, we can configure its learning process with .compile(), where you need to specify which optimizer to use, and the loss function ( categorical_crossentropy is the typical one for multi-class classification) and the metrics to track. Finally, .fit() the model by passing in the training, validation set, the number of epochs and batch size. For the batch size, we typically specify this number to be power of 2 for computing efficiency. End of explanation """ model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' del model # deletes the existing model # returns a compiled model # identical to the previous one model = load_model('my_model.h5') # testing: predict the accuracy using the loaded model y_pred = model.predict_classes(X_test, verbose = 0) accuracy = np.sum(y_test == y_pred) / X_test.shape[0] print('valid accuracy: %.2f' % (accuracy * 100)) """ Explanation: Saving and loading the models It is not recommended to use pickle or cPickle to save a Keras model. By saving it as a HDF5 file, we can preserve the configuration and weights of the model. End of explanation """
kevinjliang/Duke-Tsinghua-MLSS-2017
01C_MLP_CNN_Assignment.ipynb
apache-2.0
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # Import data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # Helper functions for creating weight variables def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # Tensorflow Functions that might also be of interest: # tf.nn.sigmoid() # tf.nn.relu() """ Explanation: TensorFlow Assignment: Multilayer Perceptron (MLP) and Convolutional Neural Network (CNN) Duke Community Standard: By typing your name below, you are certifying that you have adhered to the Duke Community Standard in completing this assignment. Name: [YOUR_NAME_HERE] Now that you've run through a simple logistic regression model on MNIST, let's see if we can do better (Hint: we can). For this assignment, you'll build a multilayer perceptron (MLP) and a convolutional neural network (CNN), two popular types of neural networks, and compare their performance. Some potentially useful code: End of explanation """ # Model Inputs x = ### MNIST images enter graph here ### y_ = ### MNIST labels enter graph here ### # Define the graph ### Create your MLP here## ### Make sure to name your MLP output as y_mlp ### # Loss cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_mlp)) # Optimizer train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # Evaluation correct_prediction = tf.equal(tf.argmax(y_mlp, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: # Initialize all variables sess.run(tf.global_variables_initializer()) # Training regimen for i in range(4000): # Validate every 250th batch if i % 250 == 0: validation_accuracy = 0 for v in range(10): batch = mnist.validation.next_batch(100) validation_accuracy += (1/10) * accuracy.eval(feed_dict={x: batch[0], y_: batch[1]}) print('step %d, validation accuracy %g' % (i, validation_accuracy)) # Train batch = mnist.train.next_batch(50) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})) """ Explanation: Multilayer Perceptron Build a multilayer perceptron for MNIST digit classfication. Feel free to play around with the model architecture and see how the training time/performance changes, but to begin, try the following: Image -> fully connected (500 hidden units) -> nonlinearity (Sigmoid/ReLU) -> fully connected (10 hidden units) -> softmax Skeleton framework for you to fill in (Code you need to provide is marked by ###): End of explanation """ # Convolutional neural network functions def conv2d(x, W): """conv2d returns a 2d convolution layer with full stride.""" return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): """max_pool_2x2 downsamples a feature map by 2X.""" return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # Tensorflow Function that might also be of interest: # tf.reshape() """ Explanation: Comparison How do the sigmoid and rectified linear unit (ReLU) compare? [Your answer here] Convolutional Neural Network Build a simple 2-layer CNN for MNIST digit classfication. Feel free to play around with the model architecture and see how the training time/performance changes, but to begin, try the following: Image -> CNN (32 5x5 filters) -> nonlinearity (ReLU) -> (2x2 max pool) -> CNN (64 5x5 filters) -> nonlinearity (ReLU) -> (2x2 max pool) -> fully connected (1024 hidden units) -> nonlinearity (ReLU) -> fully connected (10 hidden units) -> softmax Some additional functions that you might find helpful: End of explanation """ # Model Inputs x = ### MNIST images enter graph here ### y_ = ### MNIST labels enter graph here ### # Define the graph ### Create your CNN here## ### Make sure to name your CNN output as y_conv ### # Loss cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) # Optimizer train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # Evaluation correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: # Initialize all variables sess.run(tf.global_variables_initializer()) # Training regimen for i in range(10000): # Validate every 250th batch if i % 250 == 0: validation_accuracy = 0 for v in range(10): batch = mnist.validation.next_batch(50) validation_accuracy += (1/10) * accuracy.eval(feed_dict={x: batch[0], y_: batch[1]}) print('step %d, validation accuracy %g' % (i, validation_accuracy)) # Train batch = mnist.train.next_batch(50) train_step.run(feed_dict={x: batch[0], y_: batch[1]}) print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})) """ Explanation: Skeleton framework for you to fill in (Code you need to provide is marked by ###): Hint: Convolutional Neural Networks are spatial models. You'll want to transform the flattened MNIST vectors into images for the CNN. Similarly, you might want to flatten it again sometime before you do a softmax. You also might want to look into the conv2d() documentation to see what shape kernel/filter it's expecting. End of explanation """
krondor/nlp-dsx-pot
Lab 1 - IntroSpark - Student.ipynb
gpl-3.0
#Step 1.1 - Check spark version """ Explanation: Lab 1 - Hello Spark This Lab will show you how to work with Apache Spark using Python Step 1 - Working with Spark Context Step 1 - Invoke the spark context and extract what version of the spark driver application. Type<br> sc.version End of explanation """ #Step 2.1 - Create RDD of Numbers 1-10 """ Explanation: Step 2 - Working with Resilient Distributed Datasets Step 2 - Create RDD with numbers 1 to 10,<br> Extract first line,<br> Extract first 5 lines,<br> Create RDD with string "Hello Spark",<br> Extract first line.<br> Type: <br> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]<br> x_nbr_rdd = sc.parallelize(x)<br> End of explanation """ #Step 2.2 - Extract first line """ Explanation: Type: <br> x_nbr_rdd.first() End of explanation """ #Step 2.3 - Extract first 5 lines """ Explanation: Type:<br> x_nbr_rdd.take(5) End of explanation """ #Step 2.4 - Perform your first map transformation. Replace each element X in the RDD with X+1. #Remember that RDDs are IMMUTABLE, so it is not possible to UPDATE an RDD. You need to create #a NEW RDD """ Explanation: Perform a first map transformation and rpelace each element X in the RDD with X+1.<br> Type:<br> x_nbr_rdd_2 = x_nbr_rdd.map(lambda x: x+1) End of explanation """ #Step 2.5 - Check out the elements of the new RDD. Warning: Be careful with this in real life !! As you #will be bringing all elements of the RDD (from all partitions) to the driver... """ Explanation: Take a look at the elements of the new RDD.<br> Type:<br> x_nbr_rdd_2.collect() End of explanation """ #Step 2.6 - Create String RDD, Extract first line """ Explanation: Let's now create a new RDD with one string "Hello Spark" and take a look at it.<br> Type:<br> y = ["Hello Spark!"]<br> y_str_rdd = sc.parallelize(y)<br> y_str_rdd.first()<br> End of explanation """ #Step 2.7 - Create String RDD with many lines / entries, Extract first line """ Explanation: Let's now create a third RDD with several strings.<br> Type:<br> z = ["First,Line", "Second,Line", "and,Third,Line"]<br> z_str_rdd = sc.parallelize(z)<br> z_str_rdd.first() End of explanation """ #Step 2.8 - Count the number of entries in the RDD """ Explanation: Count the number of entries in this RDD.<br> Type:<br> z_str_rdd.count() End of explanation """ #Step 2.9 - Show all the entries in the RDD. Warning: Be careful with this in real life !! #As you will be bringing all elements of the RDD (from all partitions) to the driver... """ Explanation: Take a look at the elements of this RDD.<br> Type:<br> z_str_rdd.collect() End of explanation """ #Step 2.10 - Perform a map transformation to split all entries in the RDD on the commas ",". #Check out the entries in the new RDD #Notice how the entries in the new RDD are now ARRAYs with elements, where the original #strings have been split using the comma delimiter. """ Explanation: In the next step, we will split all the entries in the RDD on the commas "," <br> Type: <br> z_str_rdd_split = z_str_rdd.map(lambda line: line.split(","))<br> z_str_rdd_split.collect() End of explanation """ #Step 2.11 - Learn the difference between two transformations: map and flatMap. #Go back to the RDD z_str_rdd_split defined above using a map transformation from z_str_rdd #and use this time a flatmap. #What do you notice ? How is z_str_rdd_split_flatmap different from z_str_rdd_split ? """ Explanation: In this step, we will learn a new transformation besides map: flatMap <br> flatMap will "flatten" all the elements of an RDD entry into its subcomponents<br> This is better explained with an example<br> Type:<br> z_str_rdd_split_flatmap = z_str_rdd.flatMap(lambda line: line.split(","))<br> z_str_rdd_split_flatmap.collect() End of explanation """ #Step 2.12 - Learn the difference between two transformations: map and flatMap. #Go back to the RDD z_str_rdd_split defined above using a map transformation from z_str_rdd #and use this time a flatmap. """ Explanation: In this step, we will augment each entry in the previous RDD with the number "1" to create pairs (or tuples). The first element of the tuple will be the keyword and the second elements of the tuple will be the digit "1".<br> This is a common technic used to count elements using Spark.<br> Type:<br> countWords = z_str_rdd_split_flatmap.map(lambda word:(word,1))<br> countWords.collect() End of explanation """ #Step 2.13 - Check out the results of the aggregation #You just created an RDD countWords2 which contains the counts for each token... """ Explanation: Now we have above what is known as a PAIR RDD. Each entry in the RDD has a KEY and a VALUE.<br> The KEY is the word (First, Line, etc...) and the value is the number "1"<br> We can now AGGREGATE this RDD by summing up all the values BY KEY<br> Type:<br> from operator import add<br> countWords2 = countWords.reduceByKey(add)<br> countWords2.collect()<br> End of explanation """ #Step 3.1 - Pull data file into workbench """ Explanation: Step 3 - Count number of lines with Spark in it Step 3 - Pull in a spark README.md file, <br> Convert the file to an RDD,<br> Count the number of lines with the word "Spark" in it. <br> Type:<br> !rm README.md* -f<br> !wget https://github.com/carloapp2/SparkPOT/blob/master/README.md<br> End of explanation """ #Step 3.2 - Create RDD from data file """ Explanation: Now we will point Spark to the text file stored in the local filesystem and use the "textFile" method to create an RDD named "textfile_rdd" which will contain one entry for each line in the original text file.<br> We will also count the number of lines in the RDD (which would be as well the number of lines in the text file. <br> Type:<br> textfile_rdd = sc.textFile("README.md")<br> textfile_rdd.count()<br> End of explanation """ #Step 3.3 - Filter for only lines with word Spark """ Explanation: Let us now filter out the RDD and only keep the entries that contain the token "Spark". This will be achieved using the "filter" transformation, combined with the Python syntax for figuring out whether a particular substring is present within a larger string: substring in string.<br> We will also take a look at the first line in the newly filtered RDD. <br> Type:<br> Spark_lines = textfile_rdd.filter(lambda line: "Spark" in line)<br> Spark_lines.first()<br> End of explanation """ #Step 3.4 - count the number of lines """ Explanation: We will now count the number of entries in this filtered RDD and present the result as a concatenated string.<br> Type:<br> print "The file README.md has " + str(Spark_lines.count()) + \<br> " of " + str(textfile_rdd.count()) + \<br> " Lines with the word Spark in it."<br> End of explanation """ #Step 3.5 - count the number of instances of tokens starting with "Spark" """ Explanation: Using your knowledge from the previous exercises, you will now count the number of times the substring "Spark" appears in the original text.<br> Instructions:<br> Looking back at previous exercises, you will need to: <br> 1- Execute a flatMap transformation on the original RDD Spark_lines and split on white space.<br> 2- Augment each token with the digit "1", so as to obtain a PAIR RDD where the first element of the tuple is the token and the second element is the digit "1".<br> 3- Execute a reduceByKey with the addition to count the number of instances of each token.<br> 4- Filter the resulting RDD from Step 3- above to only keep entries which start with "Spark".<br> In Python, the syntax to decide whether a string starts with a token is string.startswith("token"). <br> 5- Display the resulting list of tokens which start with "Spark". End of explanation """ #Step 3.6 - Display the tokens which contain the substring "Spark" in them. """ Explanation: As a slight modification of the cell above, let us now filter out and display the tokens which contain the substring "Spark". (Instead of those which only START with it). Your result should be a superset of the previous result. <br> The Python syntax to determine whether a string contains a particular "token" is: "token" in string<br> End of explanation """ #Step 4.1 - Delete the file if it exists, download a new copy and load it into an RDD #Step 4.2 - Execute the necessary transformation(s) to extract the instructor's name, as well # as the instructors scores, then add up the scores per instructor and display the results # in the form of a new RDD with the elements: "Instructor Name", InstructorTotals #Step 4.3 - Execute additional transformation(s) to compute the average score per instructor. # Display the resulting averages for all instructors. """ Explanation: Step 4 - Perform analysis on a data file We have a sample file with instructors and scores. In this exercise we want you to add all scores and report on results by following these steps:<br> 1- The name of the file is "Scores.txt". Delete it from the local filesystem if it exists.<br> 2- Download the file from the provided location (see below).<br> 3- Load the text file into an RDD of instructor names and instructor scores.<br> 4- Execute a transformation which will keep the instructors names, but will add up the 4 numbers representing the scores per instructor, resulting into a new RDD<br> 5- Display the instructor's name and the total score for each instructor<br> 6- Execute a second transformation to compute the average score for each instructor and display the results.<br> 7- Who was top performer?<br> The Data File has the following format: Instructor Name,Score1,Score2,Score3,Score4<br> Here is an example line from the text file: "Carlo,5,3,3,4"<br> Data File Location: https://raw.githubusercontent.com/carloapp2/SparkPOT/master/Scores.txt End of explanation """
kubeflow/pipelines
samples/core/multiple_outputs/multiple_outputs.ipynb
apache-2.0
!python3 -m pip install 'kfp>=0.1.31' --quiet """ Explanation: Multiple outputs example This notebook is a simple example of how to make a component with multiple outputs using the Pipelines SDK. Before running notebook: Setup notebook server This pipeline requires you to setup a notebook server in the Kubeflow UI. After you are setup, upload the notebook in the Kubeflow UI and then run it in the notebook server. Create a GCS bucket This pipeline requires a GCS bucket. If you haven't already, create a GCS bucket to run the notebook. Make sure to create the storage bucket in the same project that you are running Kubeflow on to have the proper permissions by default. You can also create a GCS bucket by running gsutil mb -p &lt;project_name&gt; gs://&lt;bucket_name&gt;. Upload the notebook in the Kubeflow UI In order to run this pipeline, make sure to upload the notebook to your notebook server in the Kubeflow UI. You can clone this repo in the Jupyter notebook server by connecting to the notebook server and then selecting New > Terminal. In the terminal type git clone https://github.com/kubeflow/pipelines.git. Install Kubeflow pipelines Install the kfp package if you haven't already. End of explanation """ import kfp.deprecated as kfp import kfp.deprecated.components as components import kfp.deprecated.dsl as dsl from typing import NamedTuple """ Explanation: Setup project info and imports End of explanation """ @components.create_component_from_func def product_sum(a: float, b: float) -> NamedTuple( 'output', [('product', float), ('sum', float)]): '''Returns the product and sum of two numbers''' from collections import namedtuple product_sum_output = namedtuple('output', ['product', 'sum']) return product_sum_output(a*b, a+b) """ Explanation: Create component In order to create a component with multiple outputs, use NamedTuple with the same syntax as below. End of explanation """ @dsl.pipeline( name='multiple-outputs-pipeline', description='Sample pipeline to showcase multiple outputs' ) def pipeline(a=2.0, b=2.5, c=3.0): prod_sum_task = product_sum(a, b) prod_sum_task2 = product_sum(b, c) prod_sum_task3 = product_sum(prod_sum_task.outputs['product'], prod_sum_task2.outputs['sum']) """ Explanation: Create and run pipeline Create pipeline The pipeline parameters are specified in the pipeline function signature. End of explanation """ arguments = { 'a': 2.0, 'b': 2.5, 'c': 3.0, } run_result = kfp.Client().create_run_from_pipeline_func(pipeline, arguments=arguments) """ Explanation: Run pipeline End of explanation """
kdungs/teaching-SMD2-2016
solutions/2.ipynb
mit
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy.optimize plt.style.use('ggplot') from functools import partial """ Explanation: Übungsblatt 2: Kleinste Quadrate End of explanation """ def generate_sample(a, n=10, size=10000): ks = np.arange(1, n + 1) yss = np.random.poisson(a * ks, size=(size, n)) return ks, yss a = 4.2 ks, yss = generate_sample(a) estimators = [ ('1', lambda xs, ys: np.sum(ys * xs) / np.sum(xs ** 2)), ('1/y_k', lambda xs, ys: np.sum(xs) / np.sum(xs ** 2 / ys)), ('1/ak', lambda xs, ys: np.sqrt(np.sum(ys ** 2 / xs) / np.sum(xs))), ('1/k', lambda xs, ys: np.sum(ys) / np.sum(xs)), ('1/a_{n-1}k', lambda xs, ys: np.sum(ys) / np.sum(xs)) ] for w, wf in estimators: as_ = np.array([wf(ks, ys) for ys in yss]) mean = np.mean(as_) var = np.var(as_) plt.hist(as_, bins=20) plt.title(r'$w_k = {}$, $\mu = {:.3f}$, $\sigma^2 = {:.3f}$'.format(w, mean, var)) plt.show() """ Explanation: Aufgabe 1 Betrachten Sie $y_k, k=1,2,\dots,10$ Poisson-verteilte Messwerte um die Erwartungswerte $\mu_k = a\cdot k$. Der Parameter $a$ soll mit der Methode der kleinsten Quadrate geschätzt werden. Betrachten Sie dazu die folgenden $\chi^2$-Funktionen: $$\chi^2 = \sum_{k=1}^{10} w_k (y_k - ak)^2 \quad\text{mit}\quad w_k\in \left{1, \frac{1}{y_k}, \frac{1}{ak}, \frac{1}{k}, \frac{1}{a_{n-1}k} \right}$$ 1.1 Bestimmen Sie analytisch die Schätzwerte $\hat{a}$ als Funktion der $y_k$, welche die entsprechenden $\chi^2$-Funktion minimieren. Für den Fall $w_k = 1$ ist \begin{align} \chi^2 &= \sum_k\left(y_k - a k\right)^2 \ &= \sum_k y_k^2 - 2 y_k a k + a^2 k^2 \ \frac{\partial\chi^2}{\partial a} &= -2\sum_k y_k k + 2\sum_k a k^2 \overset{!}{=} 0 \ &\Rightarrow a \sum_k k^2 = \sum_k y_k k \ &\Rightarrow a = \frac{\sum_k y_k k}{\sum_k k^2} \end{align} Für den Fall $w_k = 1 / y_k$ ist \begin{align} \chi^2 &= \sum_k \frac{y_k^2 - 2 y_k a k + a^2 k^2}{y_k} \ &= \sum_k y_k - 2 a k + \frac{a^2 k^2}{y_k} \ \frac{\partial\chi^2}{\partial a} &= -2\sum_k k + 2a\sum_k \frac{k^2}{y_k} \overset{!}{=} 0 \ &\Rightarrow a \sum_k \frac{k^2}{y_k} = \sum_k k \ &\Rightarrow a = \frac{\sum_k k}{\sum_k \frac{k^2}{y_k}} \end{align} Für den Fall $w_k = 1 / ak$ ist \begin{align} \chi^2 &= \sum_k \frac{y_k^2 - 2 y_k a k + a^2 k^2}{ak} \ &= \sum_k \frac{y_k^2}{ak} - 2y_k + ak \ \frac{\partial\chi^2}{\partial a} &= -\frac{1}{a^2}\sum_k \frac{y_k^2}{k} + \sum_k k \overset{!}{=} 0 \ &\Rightarrow a^2 = \frac{\sum_k \frac{y_k^2}{k}}{\sum_k k} \ &\Rightarrow a = \sqrt{\frac{\sum_k \frac{y_k^2}{k}}{\sum_k k}} \end{align} Für den Fall $w_k = 1 / k$ ist \begin{align} \chi^2 &= \sum_k \frac{y_k^2 - 2 y_k a k + a^2 k^2}{k} \ &= \sum_k \frac{y_k^2}{k} - 2ay_k + a^2k \ \frac{\partial\chi^2}{\partial a} &= -2\sum_k y_k + 2a\sum_k k \overset{!}{=} 0 \ &\Rightarrow a\sum_k k = \sum_k y_k \ &\Rightarrow a = \frac{\sum_k y_k}{\sum_k k} \end{align} Für den Fall $w_k = 1 / a_{n-1} k$ ist \begin{align} \chi^2 &= \sum_k \frac{y_k^2 - 2 y_k a k + a^2 k^2}{a_{n-1}k} \ &= \sum_k \frac{y_k^2}{a_{n-1}k} - \frac{2ay_k}{a_{n-1}} + \frac{a^2k}{a_{n-1}} \ \frac{\partial\chi^2}{\partial a} &= -\frac{2}{a_{n-1}}\sum_k y_k + 2\frac{a}{a_{n-1}}\sum_k k \overset{!}{=} 0 \ &\Rightarrow \frac{a}{a_{n-1}}\sum_k k = \frac{1}{a_{n-1}}\sum_k y_k \ &\Rightarrow a = \frac{\sum_k y_k}{\sum_k k} \end{align} Das bedeutet also, dass die Minimierung in diesem Fall im ersten Schritt konvergiert und eine Iteration keine Verbesserung liefert. 1.2 Bestimmen Sie mittels Monte Carlo die Verteilungen der verschiedenen Schätzwerte $\hat{a}$. End of explanation """ def transform_x(z): return 1 / 2 * (np.sqrt(1 + 8 * z) - 1) N = np.random.poisson(400) xs = transform_x(np.random.uniform(size=N)) ns, bins, _ = plt.hist(xs, range=(0, 1), bins=10) plt.show() """ Explanation: Aufgabe 2 Betrachten Sie ein Histogramm mit 10 Bins im Bereich $[0,1]$. Generieren Sie eine Poisson-verteilte Zufallszahl $N$ mit Mittelwert $\langle N\rangle = 400$, und füllen Sie das Histogramm mit $N$ Zufallszahlen die Sie gemäß $$x = \frac{1}{2}\left(\sqrt{1 + 8z} - 1\right)$$ erzeugen, wobei $z$ gleichverteilt im Intervall $[0, 1]$ ist. Die Theorie sagt voraus, dass $x$ gemäß einer Wahrscheinlichkeitsdichte $$ \rho(x) = \frac{1 + \alpha x}{1 + \alpha/2}$$ verteilt ist. End of explanation """ def expected_ns(N, bins, alpha): widths = bins[1:] - bins[:-1] sqdiff = bins[1:] ** 2 - bins[:-1] ** 2 return N / (1 + alpha / 2) * (widths + alpha / 2 * sqdiff) tk = partial(expected_ns, N, bins) def chi2(N, bins, ns, ws, alpha): ts = expected_ns(N, bins, alpha) return np.sum(ws * (ns - ts) ** 2) c2 = partial(chi2, N, bins, ns, 1) alpha = scipy.optimize.minimize(c2, [1]).x[0] print(alpha) for _ in range(5): ws = 1 / expected_ns(N, bins, alpha) c2 = partial(chi2, N, bins, ns, ws) alpha = scipy.optimize.minimize(c2, [alpha]).x[0] print(alpha) widths = bins[1:] - bins[:-1] centres = bins[:-1] + widths / 2 plt.errorbar(centres, ns, xerr=widths / 2, yerr=np.sqrt(ns), fmt='.') def rho(x): return (1 + alpha * x) / (1 + alpha / 2) xs_ = np.linspace(0, 1, 2) plt.plot(xs_, N * widths[0] * rho(xs_)) plt.show() """ Explanation: Bestimmen sie mit der Methode der kleinsten Quadrate einen Schätzwert für $\alpha$. Nehmen Sie dazu an, dass die Anzahl der Einträge in jedem Bin Poisson-verteilt um ihren Erwartungswert streut. Beschreiben Sie die Daten durch eine lineare Funktion $y = a_0 + a1_x$, bestimmen Sie $a_0$ und $a_1$ und deren Kovarianzmatrix, und berechnen Sie daraus $\alpha(a_0, a_1)$ sowie dessen Unsicherheit. Gehen Sie beim Fit folgendermassen vor: Berechnen Sie die erwartete Zahl von Einträgen für alle Bins. Benutzen Sie diese zur Formulierung der $\chi^2$-Funktion. Minimieren Sie diese iterativ. Verwenden Sie im ersten Schritt für alle Bins konstante Gewichte $w_k = 1$, und danach als Gewicht $w_k = 1/V_k$, wobei $V_k$ die mit den Parametern aus dem vorhergehenden Fit abgeschätzte Varianz im Bin $k$ ist. Mit Hilfe der PDF können wir die Anzahl erwarteter Einträge $T_k$ im $k$-ten Bin berechnen. Es ist \begin{equation} T_k(\alpha) = N \int_{x_k}^{x_{k+1}} \mathrm{d}x\, \rho(x) = \frac{N}{1 + \alpha/2}\bigl( x_{k+1} - x_{k} + \frac{1}{2}\alpha(x_{k+1}^2 - x_k^2) \bigr) \,. \end{equation} Damit können wir unser $\chi^2$ formulieren. \begin{equation} \chi^2(\alpha) = \sum_k w_k \left(n_k - T_k(\alpha)\right)^2 \end{equation} wobei $n_k$ die beobachtete Anzahl Einträge im $k$-ten Bin ist. Wir könnten jetzt hergehen und die Funktion händisch ableiten, um unseren Schätzer zu erhalten. Um uns das Leben etwas zu vereinfachen verwenden wir die minimize-Funktion aus scipy.optimize. End of explanation """ def fit_alpha(N, xs, iterations=5): ns, bins = np.histogram(xs, range=(0, 1), bins=10) c2 = partial(chi2, N, bins, ns, 1) alpha = scipy.optimize.minimize(c2, [1]).x[0] for _ in range(iterations): ws = 1 / expected_ns(N, bins, alpha) c2 = partial(chi2, N, bins, ns, ws) alpha = scipy.optimize.minimize(c2, [alpha]).x[0] return alpha def generate_sample(mean_N=400): N = np.random.poisson(mean_N) xs = transform_x(np.random.uniform(size=N)) return N, xs alphas = np.array([fit_alpha(*generate_sample()) for _ in range(100)]) plt.hist(alphas) plt.show() print('mean = {}'.format(np.mean(alphas))) print('variance = {}'.format(np.var(alphas))) alphas = alphas[np.logical_and(-5 < alphas, alphas < 5)] plt.hist(alphas) plt.show() print('mean = {}'.format(np.mean(alphas))) print('variance = {}'.format(np.var(alphas))) """ Explanation: Wiederholen Sie die Fits mit unabhängigen Datensätzen und bestimmen Sie die Verteilung von $\alpha$. Variieren Sie die Methode, indem Sie den Fit nicht iterieren oder andere Gewichtsfunktionen benutzen. End of explanation """ def prepare_xs(xs): y, bins = np.histogram(xs) ps = bins[1:] - bins[:-1] qs = (bins[1:] ** 2 - bins[:-1] ** 2) / 2 X = np.matrix([ps, qs]).T return np.matrix(y).T, X def regression(y, X, W=None): if W is None: W = np.identity(X.shape[0]) a = (X.T * W * X).I * X.T * W * y W = (np.diag(np.array(1 / (X * a))[:,0])) return a, W N, xs = generate_sample() y, X = prepare_xs(xs) I = np.identity(np.shape(X)[0]) a, W = regression(y, X) print(a) for _ in range(10): a, W = regression(y, X, W) print(a) """ Explanation: Alternative Lösung ohne Verwendung von scipy.optimize Wir können unser $T_k$ auch als lineares Modell zweier Parameter $a_0$ und $a_1$ ausdrücken, indem wir zwei Variablen $p_k$ und $q_k$ einführen die definiert sind als \begin{align} p_k &= x_{k + 1} - x_k \,\text{und} \ q_k &= \frac{1}{2}(x_{k + 1}^2 - x_k^2) \,. \end{align} Damit ist \begin{equation} T_k(a_0, a_1) = a_0 p_k + a_1 q_k \end{equation} Damit können wir zur Minimierung des $\chi^2$ die analytische Lösung für lineare Modelle verwenden. Als Designmatrix $X$ verwenden wir \begin{equation} X = \pmatrix{p_1 & q_1 \ \vdots & \vdots \ p_k & q_k} \end{equation} und erhalten \begin{equation} \mathbf{\hat{a}} = (X^T W X)^{-1} X^T W y \end{equation} wobei $W$ die Gewichtsmatrix ist. Um $\hat{a}$ iterativ zu berechnen, verwenden wir \begin{equation} \mathbf{\hat{a}^{(n+1)}} = (X^T W^{(n)} X)^{-1} X^T W^{(n)} y \end{equation} wobei \begin{equation} W^{(n)} = \frac{1}{{\hat{a}_0^{(n)}p_k + \hat{a}_1^{(n)}q_k}} \mathbb{1} \,. \end{equation} End of explanation """ a0, a1 = a alpha = a1 / a0 alpha """ Explanation: Jetzt müssen wir nur noch $\alpha$ aus $a_0$ und $a_1$ bestimmen. End of explanation """
sraejones/phys202-2015-work
assignments/assignment06/ProjectEuler17.ipynb
mit
def number_to_words(n): """Given a number n between 1-1000 inclusive return a list of words for the number.""" # YOUR CODE HERE # English name of each digit/ place in dictionary one = { 0: '', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine' } teen = { 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', } ten = { 0: '', 2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety' } hundred = { 1: 'onehundred', 2: 'twohundred', 3: 'threehundred', 4: 'fourhundred', 5: 'fivehundred', 6: 'sixhundred', 7: 'sevenhundred', 8: 'eighthundred', 9: 'ninehundred' } hundredand = { 1: 'onehundredand', 2: 'twohundredand', 3: 'threehundredand', 4: 'fourhundredand', 5: 'fivehundredand', 6: 'sixhundredand', 7: 'sevenhundredand', 8: 'eighthundredand', 9: 'ninehundredand' } #return the name of 1-9 as a string if n in range (0, 10): return one[n] #return the name of 10-19 as a string elif n in range(10, 20): return teen[n] #return the name of 20-99 as a string elif n in range (20, 100): #turn number in to string a = str(n) #Call name of first digat from ten list b = int(a[0]) #Call name of second digat from one list c = int(a[1]) #return names as linked string return ten[b] + one[c] #return the name of 100-999 as a string elif n in range (99, 1000): #turn number into string a = str(n) #if last 2 digits are in teens if int(a[1]) == 1: #call name of first digit from hundred list b = int(a[0]) #call name of last 2 digits from teen list c = int(a[1:]) #return number as linked string return hundredand[b] + teen[c] #If it ends in a double zero if int(a[1:]) == 0: b = int(a[0]) return hundred[b] #If last 2 digits are not in teen or 00 else: #call name of first digit from hundred list d = int(a[0]) #Call name of second digat from ten list e = int(a[1]) #Call name of second digat from one list f = int(a[2]) return hundredand[d] + ten[e] + one[f] #retun onethousan if n = 1000 elif n == 1000: return 'onethousand' #If anything that is not 1 - 1000 is enterd return fail as a string else: return 'fail' """ Explanation: Project Euler: Problem 17 https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. First write a number_to_words(n) function that takes an integer n between 1 and 1000 inclusive and returns a list of words for the number as described above End of explanation """ # YOUR CODE HERE assert number_to_words(9) == 'nine' assert number_to_words(16) == 'sixteen' assert number_to_words(56) == 'fiftysix' assert number_to_words(200) == 'twohundred' assert number_to_words(315) == 'threehundredandfifteen' assert number_to_words(638) == 'sixhundredandthirtyeight' assert number_to_words(1000) == 'onethousand' assert True # use this for grading the number_to_words tests. """ Explanation: Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. End of explanation """ def count_letters(n): """Count the number of letters used to write out the words for 1-n inclusive.""" # YOUR CODE HERe #Return the length number_to_word as an integer return int(len(number_to_words(n))) """ Explanation: Now define a count_letters(n) that returns the number of letters used to write out the words for all of the the numbers 1 to n inclusive. End of explanation """ # YOUR CODE HERE assert count_letters(9) == 4 assert count_letters(16) == 7 assert count_letters(56) == 8 assert count_letters(200) == 10 assert count_letters(315) == 22 assert count_letters(638) == 24 assert count_letters(1000) == 11 assert True # use this for gradig the count_letters test. """ Explanation: Now write a set of assert tests for your count_letters function that verifies that it is working as expected. End of explanation """ # YOUR CODE HERE n = 0 i = 0 while n < 1000: n = n + 1 i = i + count_letters(n) print (i) assert True # use this for gradig the original sloution. """ Explanation: Finally used your count_letters function to solve the original question. End of explanation """
keras-team/keras-io
examples/audio/ipynb/uk_ireland_accent_recognition.ipynb
apache-2.0
!pip install -U -q tensorflow_io """ Explanation: English speaker accent recognition using Transfer Learning Author: Fadi Badine<br> Date created: 2022/04/16<br> Last modified: 2022/04/16<br> Description: Training a model to classify UK & Ireland accents using feature extraction from Yamnet. Introduction The following example shows how to use feature extraction in order to train a model to classify the English accent spoken in an audio wave. Instead of training a model from scratch, transfer learning enables us to take advantage of existing state-of-the-art deep learning models and use them as feature extractors. Our process: Use a TF Hub pre-trained model (Yamnet) and apply it as part of the tf.data pipeline which transforms the audio files into feature vectors. Train a dense model on the feature vectors. Use the trained model for inference on a new audio file. Note: We need to install TensorFlow IO in order to resample audio files to 16 kHz as required by Yamnet model. In the test section, ffmpeg is used to convert the mp3 file to wav. You can install TensorFlow IO with the following command: End of explanation """ SEED = 1337 EPOCHS = 100 BATCH_SIZE = 64 VALIDATION_RATIO = 0.1 MODEL_NAME = "uk_irish_accent_recognition" # Location where the dataset will be downloaded. # By default (None), keras.utils.get_file will use ~/.keras/ as the CACHE_DIR CACHE_DIR = None # The location of the dataset URL_PATH = "https://www.openslr.org/resources/83/" # List of datasets compressed files that contain the audio files zip_files = { 0: "irish_english_male.zip", 1: "midlands_english_female.zip", 2: "midlands_english_male.zip", 3: "northern_english_female.zip", 4: "northern_english_male.zip", 5: "scottish_english_female.zip", 6: "scottish_english_male.zip", 7: "southern_english_female.zip", 8: "southern_english_male.zip", 9: "welsh_english_female.zip", 10: "welsh_english_male.zip", } # We see that there are 2 compressed files for each accent (except Irish): # - One for male speakers # - One for female speakers # However, we will using a gender agnostic dataset. # List of gender agnostic categories gender_agnostic_categories = [ "ir", # Irish "mi", # Midlands "no", # Northern "sc", # Scottish "so", # Southern "we", # Welsh ] class_names = [ "Irish", "Midlands", "Northern", "Scottish", "Southern", "Welsh", "Not a speech", ] """ Explanation: Configuration End of explanation """ import os import io import csv import random import numpy as np import pandas as pd import tensorflow as tf import tensorflow_hub as hub import tensorflow_io as tfio from tensorflow import keras import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from IPython.display import Audio # Set all random seeds in order to get reproducible results keras.utils.set_random_seed(SEED) # Where to download the dataset DATASET_DESTINATION = os.path.join(CACHE_DIR if CACHE_DIR else "~/.keras/", "datasets") """ Explanation: Imports End of explanation """ yamnet_model = hub.load("https://tfhub.dev/google/yamnet/1") """ Explanation: Yamnet Model Yamnet is an audio event classifier trained on the AudioSet dataset to predict audio events from the AudioSet ontology. It is available on TensorFlow Hub. Yamnet accepts a 1-D tensor of audio samples with a sample rate of 16 kHz. As output, the model returns a 3-tuple: Scores of shape (N, 521) representing the scores of the 521 classes. Embeddings of shape (N, 1024). The log-mel spectrogram of the entire audio frame. We will use the embeddings, which are the features extracted from the audio samples, as the input to our dense model. For more detailed information about Yamnet, please refer to its TensorFlow Hub page. End of explanation """ # CSV file that contains information about the dataset. For each entry, we have: # - ID # - wav file name # - transcript line_index_file = keras.utils.get_file( fname="line_index_file", origin=URL_PATH + "line_index_all.csv" ) # Download the list of compressed files that contains the audio wav files for i in zip_files: fname = zip_files[i].split(".")[0] url = URL_PATH + zip_files[i] zip_file = keras.utils.get_file(fname=fname, origin=url, extract=True) os.remove(zip_file) """ Explanation: Dataset The dataset used is the Crowdsourced high-quality UK and Ireland English Dialect speech data set which consists of a total of 17,877 high-quality audio wav files. This dataset includes over 31 hours of recording from 120 vounteers who self-identify as native speakers of Southern England, Midlands, Northern England, Wales, Scotland and Ireland. For more info, please refer to the above link or to the following paper: Open-source Multi-speaker Corpora of the English Accents in the British Isles Download the data End of explanation """ dataframe = pd.read_csv( line_index_file, names=["id", "filename", "transcript"], usecols=["filename"] ) dataframe.head() """ Explanation: Load the data in a Dataframe Of the 3 columns (ID, filename and transcript), we are only interested in the filename column in order to read the audio file. We will ignore the other two. End of explanation """ # The purpose of this function is to preprocess the dataframe by applying the following: # - Cleaning the filename from a leading space # - Generating a label column that is gender agnostic i.e. # welsh english male and welsh english female for example are both labeled as # welsh english # - Add extension .wav to the filename # - Shuffle samples def preprocess_dataframe(dataframe): # Remove leading space in filename column dataframe["filename"] = dataframe.apply(lambda row: row["filename"].strip(), axis=1) # Create gender agnostic labels based on the filename first 2 letters dataframe["label"] = dataframe.apply( lambda row: gender_agnostic_categories.index(row["filename"][:2]), axis=1 ) # Add the file path to the name dataframe["filename"] = dataframe.apply( lambda row: os.path.join(DATASET_DESTINATION, row["filename"] + ".wav"), axis=1 ) # Shuffle the samples dataframe = dataframe.sample(frac=1, random_state=SEED).reset_index(drop=True) return dataframe dataframe = preprocess_dataframe(dataframe) dataframe.head() """ Explanation: Let's now preprocess the dataset by: Adjusting the filename (removing a leading space & adding ".wav" extension to the filename). Creating a label using the first 2 characters of the filename which indicate the accent. Shuffling the samples. End of explanation """ split = int(len(dataframe) * (1 - VALIDATION_RATIO)) train_df = dataframe[:split] valid_df = dataframe[split:] print( f"We have {train_df.shape[0]} training samples & {valid_df.shape[0]} validation ones" ) """ Explanation: Prepare training & validation sets Let's split the samples creating training and validation sets. End of explanation """ @tf.function def load_16k_audio_wav(filename): # Read file content file_content = tf.io.read_file(filename) # Decode audio wave audio_wav, sample_rate = tf.audio.decode_wav(file_content, desired_channels=1) audio_wav = tf.squeeze(audio_wav, axis=-1) sample_rate = tf.cast(sample_rate, dtype=tf.int64) # Resample to 16k audio_wav = tfio.audio.resample(audio_wav, rate_in=sample_rate, rate_out=16000) return audio_wav def filepath_to_embeddings(filename, label): # Load 16k audio wave audio_wav = load_16k_audio_wav(filename) # Get audio embeddings & scores. # The embeddings are the audio features extracted using transfer learning # while scores will be used to identify time slots that are not speech # which will then be gathered into a specific new category 'other' scores, embeddings, _ = yamnet_model(audio_wav) # Number of embeddings in order to know how many times to repeat the label embeddings_num = tf.shape(embeddings)[0] labels = tf.repeat(label, embeddings_num) # Change labels for time-slots that are not speech into a new category 'other' labels = tf.where(tf.argmax(scores, axis=1) == 0, label, len(class_names) - 1) # Using one-hot in order to use AUC return (embeddings, tf.one_hot(labels, len(class_names))) def dataframe_to_dataset(dataframe, batch_size=64): dataset = tf.data.Dataset.from_tensor_slices( (dataframe["filename"], dataframe["label"]) ) dataset = dataset.map( lambda x, y: filepath_to_embeddings(x, y), num_parallel_calls=tf.data.experimental.AUTOTUNE, ).unbatch() return dataset.cache().batch(batch_size).prefetch(tf.data.AUTOTUNE) train_ds = dataframe_to_dataset(train_df) valid_ds = dataframe_to_dataset(valid_df) """ Explanation: Prepare a TensorFlow Dataset Next, we need to create a tf.data.Dataset. This is done by creating a dataframe_to_dataset function that does the following: Create a dataset using filenames and labels. Get the Yamnet embeddings by calling another function filepath_to_embeddings. Apply caching, reshuffling and setting batch size. The filepath_to_embeddings does the following: Load audio file. Resample audio to 16 kHz. Generate scores and embeddings from Yamnet model. Since Yamnet generates multiple samples for each audio file, this function also duplicates the label for all the generated samples that have score=0 (speech) whereas sets the label for the others as 'other' indicating that this audio segment is not a speech and we won't label it as one of the accents. The below load_16k_audio_file is copied from the following tutorial Transfer learning with YAMNet for environmental sound classification End of explanation """ keras.backend.clear_session() def build_and_compile_model(): inputs = keras.layers.Input(shape=(1024), name="embedding") x = keras.layers.Dense(256, activation="relu", name="dense_1")(inputs) x = keras.layers.Dropout(0.15, name="dropout_1")(x) x = keras.layers.Dense(384, activation="relu", name="dense_2")(x) x = keras.layers.Dropout(0.2, name="dropout_2")(x) x = keras.layers.Dense(192, activation="relu", name="dense_3")(x) x = keras.layers.Dropout(0.25, name="dropout_3")(x) x = keras.layers.Dense(384, activation="relu", name="dense_4")(x) x = keras.layers.Dropout(0.2, name="dropout_4")(x) outputs = keras.layers.Dense(len(class_names), activation="softmax", name="ouput")( x ) model = keras.Model(inputs=inputs, outputs=outputs, name="accent_recognition") model.compile( optimizer=keras.optimizers.Adam(learning_rate=1.9644e-5), loss=keras.losses.CategoricalCrossentropy(), metrics=["accuracy", keras.metrics.AUC(name="auc")], ) return model model = build_and_compile_model() model.summary() """ Explanation: Build the model The model that we use consists of: An input layer which is the embedding output of the Yamnet classifier. 4 dense hidden layers and 4 dropout layers. An output dense layer. The model's hyperparameters were selected using KerasTuner. End of explanation """ class_counts = tf.zeros(shape=(len(class_names),), dtype=tf.int32) for x, y in iter(train_ds): class_counts = class_counts + tf.math.bincount( tf.cast(tf.math.argmax(y, axis=1), tf.int32), minlength=len(class_names) ) class_weight = { i: tf.math.reduce_sum(class_counts).numpy() / class_counts[i].numpy() for i in range(len(class_counts)) } print(class_weight) """ Explanation: Class weights calculation Since the dataset is quite unbalanced, we wil use class_weight argument during training. Getting the class weights is a little tricky because even though we know the number of audio files for each class, it does not represent the number of samples for that class since Yamnet transforms each audio file into multiple audio samples of 0.96 seconds each. So every audio file will be split into a number of samples that is proportional to its length. Therefore, to get those weights, we have to calculate the number of samples for each class after preprocessing through Yamnet. End of explanation """ early_stopping_cb = keras.callbacks.EarlyStopping( monitor="val_auc", patience=10, restore_best_weights=True ) model_checkpoint_cb = keras.callbacks.ModelCheckpoint( MODEL_NAME + ".h5", monitor="val_auc", save_best_only=True ) tensorboard_cb = keras.callbacks.TensorBoard( os.path.join(os.curdir, "logs", model.name) ) callbacks = [early_stopping_cb, model_checkpoint_cb, tensorboard_cb] """ Explanation: Callbacks We use Keras callbacks in order to: Stop whenever the validation AUC stops improving. Save the best model. Call TensorBoard in order to later view the training and validation logs. End of explanation """ history = model.fit( train_ds, epochs=EPOCHS, validation_data=valid_ds, class_weight=class_weight, callbacks=callbacks, verbose=2, ) """ Explanation: Training End of explanation """ fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(14, 5)) axs[0].plot(range(EPOCHS), history.history["accuracy"], label="Training") axs[0].plot(range(EPOCHS), history.history["val_accuracy"], label="Validation") axs[0].set_xlabel("Epochs") axs[0].set_title("Training & Validation Accuracy") axs[0].legend() axs[0].grid(True) axs[1].plot(range(EPOCHS), history.history["auc"], label="Training") axs[1].plot(range(EPOCHS), history.history["val_auc"], label="Validation") axs[1].set_xlabel("Epochs") axs[1].set_title("Training & Validation AUC") axs[1].legend() axs[1].grid(True) plt.show() """ Explanation: Results Let's plot the training and validation AUC and accuracy. End of explanation """ train_loss, train_acc, train_auc = model.evaluate(train_ds) valid_loss, valid_acc, valid_auc = model.evaluate(valid_ds) """ Explanation: Evaluation End of explanation """ # The following function calculates the d-prime score from the AUC def d_prime(auc): standard_normal = stats.norm() d_prime = standard_normal.ppf(auc) * np.sqrt(2.0) return d_prime print( "train d-prime: {0:.3f}, validation d-prime: {1:.3f}".format( d_prime(train_auc), d_prime(valid_auc) ) ) """ Explanation: Let's try to compare our model's performance to Yamnet's using one of Yamnet metrics (d-prime) Yamnet achieved a d-prime value of 2.318. Let's check our model's performance. End of explanation """ # Create x and y tensors x_valid = None y_valid = None for x, y in iter(valid_ds): if x_valid is None: x_valid = x.numpy() y_valid = y.numpy() else: x_valid = np.concatenate((x_valid, x.numpy()), axis=0) y_valid = np.concatenate((y_valid, y.numpy()), axis=0) # Generate predictions y_pred = model.predict(x_valid) # Calculate confusion matrix confusion_mtx = tf.math.confusion_matrix( np.argmax(y_valid, axis=1), np.argmax(y_pred, axis=1) ) # Plot the confusion matrix plt.figure(figsize=(10, 8)) sns.heatmap( confusion_mtx, xticklabels=class_names, yticklabels=class_names, annot=True, fmt="g" ) plt.xlabel("Prediction") plt.ylabel("Label") plt.title("Validation Confusion Matrix") plt.show() """ Explanation: We can see that the model achieves the following results: Results | Training | Validation -----------|-----------|------------ Accuracy | 54% | 51% AUC | 0.91 | 0.89 d-prime | 1.882 | 1.740 Confusion Matrix Let's now plot the confusion matrix for the validation dataset. The confusion matrix lets us see, for every class, not only how many samples were correctly classified, but also which other classes were the samples confused with. It allows us to calculate the precision and recall for every class. End of explanation """ for i, label in enumerate(class_names): precision = confusion_mtx[i, i] / np.sum(confusion_mtx[:, i]) recall = confusion_mtx[i, i] / np.sum(confusion_mtx[i, :]) print( "{0:15} Precision:{1:.2f}%; Recall:{2:.2f}%".format( label, precision * 100, recall * 100 ) ) """ Explanation: Precision & recall For every class: Recall is the ratio of correctly classified samples i.e. it shows how many samples of this specific class, the model is able to detect. It is the ratio of diagonal elements to the sum of all elements in the row. Precision shows the accuracy of the classifier. It is the ratio of correctly predicted samples among the ones classified as belonging to this class. It is the ratio of diagonal elements to the sum of all elements in the column. End of explanation """ filename = "audio-sample-Stuart" url = "https://www.thescottishvoice.org.uk/files/cm/files/" if os.path.exists(filename + ".wav") == False: print(f"Downloading {filename}.mp3 from {url}") command = f"wget {url}{filename}.mp3" os.system(command) print(f"Converting mp3 to wav and resampling to 16 kHZ") command = ( f"ffmpeg -hide_banner -loglevel panic -y -i {filename}.mp3 -acodec " f"pcm_s16le -ac 1 -ar 16000 {filename}.wav" ) os.system(command) filename = filename + ".wav" """ Explanation: Run inference on test data Let's now run a test on a single audio file. Let's check this example from The Scottish Voice We will: Download the mp3 file. Convert it to a 16k wav file. Run the model on the wav file. Plot the results. End of explanation """ def yamnet_class_names_from_csv(yamnet_class_map_csv_text): """Returns list of class names corresponding to score vector.""" yamnet_class_map_csv = io.StringIO(yamnet_class_map_csv_text) yamnet_class_names = [ name for (class_index, mid, name) in csv.reader(yamnet_class_map_csv) ] yamnet_class_names = yamnet_class_names[1:] # Skip CSV header return yamnet_class_names yamnet_class_map_path = yamnet_model.class_map_path().numpy() yamnet_class_names = yamnet_class_names_from_csv( tf.io.read_file(yamnet_class_map_path).numpy().decode("utf-8") ) def calculate_number_of_non_speech(scores): number_of_non_speech = tf.math.reduce_sum( tf.where(tf.math.argmax(scores, axis=1, output_type=tf.int32) != 0, 1, 0) ) return number_of_non_speech def filename_to_predictions(filename): # Load 16k audio wave audio_wav = load_16k_audio_wav(filename) # Get audio embeddings & scores. scores, embeddings, mel_spectrogram = yamnet_model(audio_wav) print( "Out of {} samples, {} are not speech".format( scores.shape[0], calculate_number_of_non_speech(scores) ) ) # Predict the output of the accent recognition model with embeddings as input predictions = model.predict(embeddings) return audio_wav, predictions, mel_spectrogram """ Explanation: The below function yamnet_class_names_from_csv was copied and very slightly changed from this Yamnet Notebook. End of explanation """ audio_wav, predictions, mel_spectrogram = filename_to_predictions(filename) infered_class = class_names[predictions.mean(axis=0).argmax()] print(f"The main accent is: {infered_class} English") """ Explanation: Let's run the model on the audio file: End of explanation """ Audio(audio_wav, rate=16000) """ Explanation: Listen to the audio End of explanation """ plt.figure(figsize=(10, 6)) # Plot the waveform. plt.subplot(3, 1, 1) plt.plot(audio_wav) plt.xlim([0, len(audio_wav)]) # Plot the log-mel spectrogram (returned by the model). plt.subplot(3, 1, 2) plt.imshow( mel_spectrogram.numpy().T, aspect="auto", interpolation="nearest", origin="lower" ) # Plot and label the model output scores for the top-scoring classes. mean_predictions = np.mean(predictions, axis=0) top_class_indices = np.argsort(mean_predictions)[::-1] plt.subplot(3, 1, 3) plt.imshow( predictions[:, top_class_indices].T, aspect="auto", interpolation="nearest", cmap="gray_r", ) # patch_padding = (PATCH_WINDOW_SECONDS / 2) / PATCH_HOP_SECONDS # values from the model documentation patch_padding = (0.025 / 2) / 0.01 plt.xlim([-patch_padding - 0.5, predictions.shape[0] + patch_padding - 0.5]) # Label the top_N classes. yticks = range(0, len(class_names), 1) plt.yticks(yticks, [class_names[top_class_indices[x]] for x in yticks]) _ = plt.ylim(-0.5 + np.array([len(class_names), 0])) """ Explanation: The below function was copied from this Yamnet notebook and adjusted to our need. This function plots the following: Audio waveform Mel spectrogram Predictions for every time step End of explanation """
dataventures/workshops
4/0-Time-Series-Analysis.ipynb
mit
import pandas as pd import numpy as np import matplotlib.pylab as plt %matplotlib inline from matplotlib.pylab import rcParams rcParams['figure.figsize'] = 15, 6 """ Explanation: Time Series Analysis and Forecasting Sometimes the data we're working with has a special dependence on time as its primary predictive feature, and we want to predict how a variable evolves with time. These situations occur all of the time, from predicting stock prices to tomorrow's weather. In these cases, the data is called a time series, and we can apply a special set of statistical methods for analyzing the data. Time Series Exploration With Pandas End of explanation """ dateparse = lambda dates: pd.datetime.strptime(dates, '%Y-%m') data = pd.read_csv('AirPassengers.csv', parse_dates=['Month'], index_col='Month',date_parser=dateparse) print data.head() """ Explanation: Pandas has great support for datetime objects and general time series analysis operations. We'll be working with an example of predicting the number of airline passengers (in thousands) by month adapted from this tutorial. First, download this dataset and load it into a Pandas Dataframe by specifying the 'Month' column as the datetime index. End of explanation """ ts = data["#Passengers"] ts.index """ Explanation: Note that Pandas is using the 'Month' column as the Dataframe index. End of explanation """ ts['1949-01-01'] from datetime import datetime ts[datetime(1949,1,1)] """ Explanation: We can index into the Dataframe in two ways - either by using a string representation for the index or by constructing a datetime object. End of explanation """ ts['1949'] ts['1949-01-01':'1949-05-01'] """ Explanation: We can also use the Pandas datetime index support to retrieve entire years End of explanation """ plt.plot(ts) """ Explanation: Finally, let's plot the time series to get an intial visualization of how the series grows. End of explanation """ ts_log = np.log(ts) plt.plot(ts_log) """ Explanation: Stationarity Most of the important results for time series forecasting (including the ARIMA model, which we focus on today) assume that the series is stationary - that is, its statistical properties like mean and variance are constant. However, the graph above certainly isn't stationary, given the obvious growth. Thus, we want to manipulate the time series to make it stationary. This process of reducing a time series to a stationary series is a hallmark of time series analysis and forecasting, as most real world time series' aren't initially stationary. To solve this nonstationarity issue, we can break a time series up into its trend and seasonality. These are the two factors that make a series nonstationary, so the main idea is to remove these factors, operate on the resulting stationary series, then add these factors back in. First, we will take the log of the series to reduce the positive trend. This gives a seemingly linear trend, making it easier to estimate. End of explanation """ moving_avg = pd.Series(ts_log).rolling(window=12).mean() plt.plot(ts_log) plt.plot(moving_avg, color='red') """ Explanation: A simple moving average is the most basic way to predict the trend of a series, taking advantage of the generally continuous nature of trends. For example, if I told you to predict the number of wins of a basketball team this season, without giving you any information about the team apart from its past record, you would take the average of the team's wins over the last few seasons as a reasonable predictor. The simple moving average operates on this exact principle. Choosing an $n$ element window to average over, the prediction at each point is obtained by taking the average of the last $n$ values. Notice that the moving average is undefined for first 12 values because we're looking at a 12 value window. End of explanation """ expwighted_avg = pd.Series(ts_log).ewm(halflife=12).mean() plt.plot(ts_log) plt.plot(expwighted_avg, color='red') """ Explanation: You might be unhappy with having to choose a window size. How do we know what window size we want if we don't know much about the data? One solution is to average over all past data, discounting earlier values because they have less predictive power than more recent values. This method is known as smoothing. End of explanation """ ts_exp_moving_avg_diff = ts_log - expwighted_avg ts_log_moving_avg_diff = ts_log - moving_avg ts_log_moving_avg_diff.dropna(inplace=True) plt.plot(ts_exp_moving_avg_diff) plt.plot(ts_log_moving_avg_diff, color='red') """ Explanation: Now we can subtract the trend from the original data (eliminating the null values in the case of the simple moving average) to create a new series that is hopefully more stationary. The blue graph represents the smoothing difference, while the red graph represents the simple moving average difference End of explanation """ ts_log_diff = ts_log - ts_log.shift() plt.plot(ts_log_diff) """ Explanation: Now there is no longer an upward trend, suggesting a stationarity. There does seem to be a strong seasonality effect, as the number of passengers is low at the beginning and middle of the year but spikes at the first and third quarters. Dealing with Seasonality One baseline way of dealing with both trend and seasonality at once is differencing, taking a single step lag (subtracting the last value of the series from the current value at each step) to represent how the time series grows. Of course, this method can be refined by factoring in more complex lags. End of explanation """ from statsmodels.tsa.seasonal import seasonal_decompose decomposition = seasonal_decompose(ts_log) trend = decomposition.trend seasonal = decomposition.seasonal residual = decomposition.resid plt.subplot(411) plt.plot(ts_log, label='Original') plt.legend(loc='best') plt.subplot(412) plt.plot(trend, label='Trend') plt.legend(loc='best') plt.subplot(413) plt.plot(seasonal,label='Seasonality') plt.legend(loc='best') plt.subplot(414) plt.plot(residual, label='Residuals') plt.legend(loc='best') plt.tight_layout() """ Explanation: Another method of dealing with trend and seasonality is separating the two effects, then removing both from the time series to obtain the stationary series. We'll be using the statsmodels module, which you can get via pip by running the following command in the terminal. python -mpip install statsmodels We will use the seasonal decompose tool to separate seasonality from trend. End of explanation """ from statsmodels.tsa.arima_model import ARIMA model = ARIMA(ts_log, order=(2, 1, 2)) results_ARIMA = model.fit(disp=-1) plt.plot(ts_log_diff) plt.plot(results_ARIMA.fittedvalues, color='red') plt.title('RSS: %.4f'% sum((results_ARIMA.fittedvalues-ts_log_diff)**2)) """ Explanation: Forecasting Using the seasonal decomposition, we were able to separate the trend and seasonality effects, which is great for time series analysis. However, another goal of working with time series is forecasting the future - how do we do that given the tools that we've been using and the stationary series we've obtained? The ARIMA (Autoregressive Integrated Moving Average) model, which operates on stationary series', is one of the most commonly used models for time series forecasting. ARIMA, with parameters $p$, $d$, and $q$, combines an Autoregressive Model with a Moving Average model. Let's take a look at what this means. Autoregressive model: output variable depends linearly on previous values. The $p$ parameter determines the number of lag terms used in the regression. Formally, $X_t = c + \sum_{i = 1}^p \varphi_iX_{t - i} + \epsilon_t$. Moving average model: generalizes the same concept of moving average we saw earlier - the $q$ parameter determines the order of the model. Formally, $X_t = \mu + \sum_{i = 1}^q \theta_i\epsilon_{t - i}$. Integrated model: the $d$ parameter represents the number of times past values have been subtracted, extending on the differencing method described earlier. This integrates the differencing for stationality into the ARIMA model, allowing it to be fit on non-stationalized data. We don't have time to cover the math behind these models in depth, but Wikipedia provides some more detailed descriptions of the AR, MA, ARMA, and ARIMA models. Comparing our model's results (red) to the actual differenced data (blue). End of explanation """ predictions_ARIMA_diff = pd.Series(results_ARIMA.fittedvalues, copy=True) predictions_ARIMA_diff_cumsum = predictions_ARIMA_diff.cumsum() predictions_ARIMA_log = pd.Series(ts_log.ix[0], index=ts_log.index) predictions_ARIMA_log = predictions_ARIMA_log.add(predictions_ARIMA_diff_cumsum,fill_value=0) """ Explanation: Now that we have a model for the stationary series that we can use to predict future values in the stationary series, and we want to get back to the original series. Note that we won't have a value for the first element because we are working with a one step lag. The following procedure takes care of that. End of explanation """ predictions_ARIMA = np.exp(predictions_ARIMA_log) plt.plot(ts) plt.plot(predictions_ARIMA) plt.title('RMSE: %.4f'% np.sqrt(sum((predictions_ARIMA-ts)**2)/len(ts))) """ Explanation: Now, we can plot the prediction (green) against the actual data. Note that the prediction model captures the seasonality and trend of the original series. It's not perfect, and additional steps can be made to tune the model. The important takeaway from this workshop is the general time series procedure of separating the time series into the trend and seasonality effects, and understanding how to work with time series' in Pandas. End of explanation """ # TODO: adjust the p, d, and q parameters to model the AR, MA, and ARMA models. Then, adjust these parameters to optimally tune the ARIMA model. test_model = ARIMA(ts_log, order=(2, 1, 2)) test_results_ARIMA = test_model.fit(disp=-1) test_predictions_ARIMA_diff = pd.Series(test_results_ARIMA.fittedvalues, copy=True) test_predictions_ARIMA_diff_cumsum = test_predictions_ARIMA_diff.cumsum() test_predictions_ARIMA_log = pd.Series(ts_log.ix[0], index=ts_log.index) test_predictions_ARIMA_log = test_predictions_ARIMA_log.add(test_predictions_ARIMA_diff_cumsum,fill_value=0) test_predictions_ARIMA = np.exp(test_predictions_ARIMA_log) plt.plot(ts) plt.plot(test_predictions_ARIMA) plt.title('RMSE: %.4f'% np.sqrt(sum((test_predictions_ARIMA-ts)**2)/len(ts))) """ Explanation: Challenge: ARIMA Tuning This is an open ended challenge. There aren't any right or wrong answers, we'd just like to see how you would approach tuning the ARIMA model. As you can see above, the ARIMA predictions could certainly use some tuning. Try manually tuning $p$, $d$, and $q$ and see how that changes the ARIMA predictions. How would you use the AR, MA, and ARMA models individually using the ARIMA model? Do these results match what you would expect from these individual models? Can you automate this process to find the parameters that minimize RMSE? Do you see any issues with tuning $p$, $d$ and $q$ this way? End of explanation """
sdpython/pyquickhelper
_unittests/ut_helpgen/notebooks_svg/seance4_projection_population_correction.ipynb
mit
from jyquickhelper import add_notebook_menu add_notebook_menu() """ Explanation: Evolutation d'une population (correction) End of explanation """ from actuariat_python.data import population_france_2015 population = population_france_2015() df = population df.head(n=3) hommes = df["hommes"] femmes = df["femmes"] somme = hommes - femmes """ Explanation: Exercice 1 : pyramides des âges End of explanation """ from matplotlib import pyplot as plt from numpy import arange plt.style.use('ggplot') fig, ax = plt.subplots(figsize=(8,8)) ValH = ax.barh(arange(len(hommes)),hommes,1.0,label="Hommes",color='b',linewidth=0,align='center') ValF = ax.barh(arange(len(femmes)),-femmes,1.0,label="Femmes",color='r',linewidth=0,align='center') diff, = ax.plot(somme,arange(len(femmes)),'y',linewidth=2) ax.set_title("Pyramide des âges") ax.set_ylabel("Ages") ax.set_xlabel("Habitants") ax.set_ylim([0,110]) ax.legend((ValH[0],ValF[0],diff),('Hommes','Femmes','différence')) """ Explanation: Je reprends ici le code exposé à Damien Vergnaud's Homepage en l'adaptant un peu avec les fonctions de matplotlib via l'interface pyplot. Puis j'ajoute la différence par âge. On commence souvent par la gallerie pour voir si un graphe ou juste une partie est similaire à ce qu'on veut obtenir. End of explanation """ from actuariat_python.plots import plot_population_pyramid plot_population_pyramid(df["hommes"], df["femmes"], figsize=(8,4)) """ Explanation: Le même en utilisant la fonction insérée dans le module actuariat_python. End of explanation """ from actuariat_python.data import table_mortalite_france_00_02 df=table_mortalite_france_00_02() import pandas pandas.concat([ df.head(n=3), df.tail(n=3) ]) """ Explanation: Exercice 2 : calcul de l'espérance de vie Le premier objectif est de calculer l'espérance de vie à l'âge $t$ à partir de la table de mortalité. On récupère cette table. End of explanation """ import numpy hf = df[["Homme", "Femme"]].as_matrix() hf = numpy.vstack([hf, numpy.zeros((8,2))]) hf.shape nb = hf.shape[0] esp = numpy.zeros ((nb,2)) for t in range(0,nb): for i in (0,1): if hf[t,i] == 0: esp[t,i] = 0 else: somme = 0.0 for d in range(1,nb-t): if hf[t+d,i] > 0: somme += d * (hf[t+d,i] - hf[t+d+1,i]) / hf[t,i] esp[t,i] = somme esp[:1] """ Explanation: On note $P_t$ la population l'âge $t$. La probabilité de mourir à la date $t+d$ lorsqu'on a l'âge $t$ correspond à la probabilité de rester en vie à jusqu'à l'âge $t+d$ puis de mourir dans l'année qui suit : $$m_{t+d} = \frac{P_{t+d}}{P_t}\frac{P_{t+d} - P_{t+d+1}}{P_{t+d}} $$. L'espérance de vie s'exprime : $$\mathbb{E}(t) = \sum_{d=1}^\infty d m_{t+d} = \sum_{d=1}^\infty d \frac{P_{t+d}}{P_t}\frac{P_{t+d} - P_{t+d+1}}{P_{t+d}} = \sum_{d=1}^\infty d \frac{P_{t+d} - P_{t+d+1}}{P_{t}} $$ On crée une matrice allant de 0 à 120 ans et on pose $\mathbb{E}(120)=0$. On utilise le module numpy. End of explanation """ from matplotlib import pyplot as plt plt.style.use('ggplot') h = plt.plot(esp) plt.legend(h, ["Homme", "Femme"]) plt.title("Espérance de vie") """ Explanation: Enfin, on dessine le résultat avec matplotlib : End of explanation """ # à suivre """ Explanation: Le calcul implémenté ci-dessus n'est pas le plus efficace. On fait deux boucles imbriquées dont le coût global est en $O(n^2)$ mais surtout on effectue les mêmes calculs plusieurs fois. Pour le réduire à un coût linéaire $O(n)$, il faut s'intéresser à la quantité : $$P_{t+1} \mathbb{E}(t+1) - P_t \mathbb{E}(t) = \sum_{d=1}^\infty d (P_{t+d+1} - P_{t+d+2}) - \sum_{d=1}^\infty d (P_{t+d} - P_{t+d+1})$$ L'implémentation devra utiliser la fonction numpy.cumsum et cette astuce Pandas Dataframe cumsum by row in reverse column order?. End of explanation """ mortalite = (hf[:-1] - hf[1:]) / hf[:-1] mortalite = numpy.nan_to_num(mortalite) # les divisions nulles deviennent nan, on les remplace par 0 mortalite = numpy.vstack([mortalite, numpy.zeros((1,2))]) m = mortalite """ Explanation: numpy et pandas ont plusieurs fonction en commun dès qu'il s'agit de parcourir les données. Il existe aussi la fonction DataFrame.cumsum. Exercice 3 : simulation de la pyramide en 2016 L'objectif est d'estimer la population française en 2016. Si $P(a,2015)$ désigne le nombre de personnes d'âge $a$ en 2015, on peut estimer $P(a,2016)$ en utilisant la probabilité de mourir $m(a)$ : $$ P(a+1, 2016) = P(a,2015) * (1 - m(a))$$ On commence par calculer les coefficients $m(a)$ avec la table hf obtenue lors de l'exercice précédent tout en gardant la même dimension (on aura besoin de la fonction nan_to_num : End of explanation """ pop = population[["hommes","femmes"]].as_matrix() pop = numpy.vstack( [pop, numpy.zeros((m.shape[0] - pop.shape[0],2))]) pop.shape """ Explanation: La population a été obtenue lors de l'exercice 1, on la convertit en un objet numpy : End of explanation """ pop_next = pop * (1-m) pop_next = numpy.vstack([numpy.zeros((1,2)), pop_next[:-1]]) pop_next[:5] pop[:5] from actuariat_python.plots import plot_population_pyramid plot_population_pyramid(pop_next[:,0], pop_next[:,1]) """ Explanation: Ensuite on calcule la population en 2016 : End of explanation """ def iteration(pop, mortalite): pop_next = pop * (1-mortalite) pop_next = numpy.vstack([numpy.zeros((1,2)), pop_next[:-1]]) # aucune naissance return pop_next popt = pop for year in range(2016, 2051): popt = iteration(popt, mortalite) plot_population_pyramid(popt[:,0], popt[:,1], title="Pyramide des âges en 2050") """ Explanation: Exercice 4 : simulation jusqu'en 2100 Il s'agit de répéter l'itération effectuée lors de l'exercice précédent. Le plus est de recopier le code dans une fonction et de l'appeler un grand nombre de fois. End of explanation """ ratio = pop[0,0] / (pop[0,1] + pop[0,0]) ratio """ Explanation: Exercice 5 : simulation avec les naissances Dans l'exercice précédent, la seconde ligne de la fonction iteration correspond à cas où il n'y a pas de naissance. On veut remplacer cette ligne par quelque chose proche de la réalité : les naissances sont calculées à partir de la population féminines et de la table de fécondité on garde la même proportion homme/femme que celle actuellement observée End of explanation """ from actuariat_python.data import fecondite_france df=fecondite_france() df.head() from matplotlib import pyplot as plt df.plot(x="age", y=["2004","2014"]) """ Explanation: Il y a un peu plus de garçons qui naissent chaque année. End of explanation """ ages = pandas.DataFrame(dict(age=range(0,120))) merge = ages.merge(df, left_on="age", right_on="age", how="outer") fecondite = merge.fillna(0.0) fecondite[13:17] mat_fec = fecondite[["2014"]].as_matrix() / 1000 # les chiffres sont pour 1000 femmes mat_fec.shape """ Explanation: On convertit ces données en une matrice numpy sur 120 lignes comme les précédentes. On se sert des méthodes fillna et merge. End of explanation """ def naissances(pop, fec): # on suppose que pop est une matrice avec deux colonnes homme, femme # et que fec est une matrice avec une colonne fécondité n = pop[:,1] * fec[:,0] return n.sum() nais = naissances(pop, mat_fec) nais """ Explanation: Il faut maintenant coder une fonction qui calcule le naissances pour l'année suivantes. End of explanation """ def iteration(pop, mortalite, fec, ratio): pop_next = pop * (1-mortalite) nais = naissances(pop, fec) row = numpy.array([[nais*ratio, nais*(1-ratio)]]) pop_next = numpy.vstack([row, pop_next[:-1]]) # aucune naissance return pop_next popt = pop for year in range(2016, 2051): popt = iteration(popt, m, mat_fec, ratio) plot_population_pyramid(popt[:,0], popt[:,1], title="Pyramide des âges en 2050") """ Explanation: Et on reprend la fonction iteration et le code de l'exercice précédent : End of explanation """ total = [[2015, pop[:,0].sum(),pop[:,1].sum()]] popt = pop for year in range(2016, 2101): popt = iteration(popt, m, mat_fec, ratio) total.append([year, popt[:,0].sum(),popt[:,1].sum()]) plot_population_pyramid(popt[:,0], popt[:,1], title="Pyramide des âges en 2101") df = pandas.DataFrame(data=total, columns=["année","hommes","femmes"]) df.plot(x="année", y=["hommes", "femmes"], title="projection population française") """ Explanation: On va plus loin et on stocke la population dans un vecteur : End of explanation """ from matplotlib import pyplot as plt fig, ax = plt.subplots(1,2,figsize=(14,6)) plot_population_pyramid(popt[:,0], popt[:,1], title="Pyramide des âges en 2050", ax=ax[0]) df.plot(x="année", y=["hommes", "femmes"], title="projection population française", ax=ax[1]) """ Explanation: Le code suivant permet de combiner les deux graphes sur la même ligne avec la fonction subplots : End of explanation """ from actuariat_python.data import population_france_2015 population = population_france_2015() population.head(n=3) from IPython.display import SVG import pygal pyramid_chart = pygal.Pyramid(human_readable=True, legend_at_bottom=True) pyramid_chart.title = 'Population française en 2015' pyramid_chart.x_labels = map(lambda x: str(x) if not x % 5 else '', population["age"]) pyramid_chart.add("hommes", population["hommes"]) pyramid_chart.add("femmes", population["femmes"]) SVG(pyramid_chart.render()) """ Explanation: Autre représentation d'une pyramide avec le module pygal Le code suivant utilise le module pygal et le notebook Interactive plots in IPython notebook using pygal ou celui-ci pygal.ipynb . End of explanation """
ernestyalumni/MLgrabbag
nVidia_entrevue/Halloween_candy_max.ipynb
mit
sample_input_arr = np.array([5,10,2,4,3,2,1],dtype=np.int32) f = np.savetxt("sample_input.txt", sample_input_arr, fmt='%i',delimiter="\n") N_H = 10 # <= 10000 C_max = 5 # <= 1000 c_low = 0 c_high = 10 filename = "sample_input_1.txt" homes = np.random.randint(low=c_low,high=c_high, size=N_H) input_arr = np.insert(homes,0,C_max,axis=0) input_arr = np.insert(input_arr,0,N_H,axis=0) np.savetxt(filename, input_arr , fmt='%i', delimiter="\n") N_H = 500 # <= 10000 C_max = 1000 # <= 1000 c_low = 0 c_high = 1000 filename = "sample_input_2.txt" homes = np.random.randint(low=c_low,high=c_high, size=N_H) input_arr = np.insert(homes,0,C_max,axis=0) input_arr = np.insert(input_arr,0,N_H,axis=0) np.savetxt(filename, input_arr , fmt='%i', delimiter="\n") N_H = 8000 # <= 10000 C_max = 800 # <= 1000 c_low = 0 c_high = 1000 filename = "sample_input_3.txt" homes = np.random.randint(low=c_low,high=c_high, size=N_H) input_arr1 = np.insert(homes,0,C_max,axis=0) input_arr1 = np.insert(input_arr1,0,N_H,axis=0) np.savetxt(filename, input_arr1 , fmt='%i', delimiter="\n") N_H = 8000 # <= 10000 C_max = 800 # <= 1000 c_low = 0 c_high = 100 filename = "sample_input_4.txt" homes = np.random.randint(low=c_low,high=c_high, size=N_H) input_arr2 = np.insert(homes,0,C_max,axis=0) input_arr2 = np.insert(input_arr2,0,N_H,axis=0) np.savetxt(filename, input_arr2 , fmt='%i', delimiter="\n") """ Explanation: Sample input data creation End of explanation """ case0_input_arr = np.arange(10,16) case0_input_arr = np.insert( case0_input_arr,0,case0_input_arr.size-1,axis=0) np.savetxt("case0_input.txt", case0_input_arr , fmt='%i', delimiter="\n") """ Explanation: Make an artificial case where we expect to not go to any of the houses (too much candy from each home, as each home gives more than the maximum alloted pieces of candy) End of explanation """ def main_loop_draft(input_arr): N_H = input_arr[0] C_max = input_arr[1] homes_arr = input_arr[2:] result = np.zeros(3,dtype=int) for h_0 in range(1, N_H +1): for h_1 in range(h_0, N_H +1): c_sum = homes_arr[h_0-1:h_1].sum() # be aware of 0-based counting, i.e. counting from 0, of Python and C/C++ if (c_sum > C_max): break elif (c_sum == C_max): # obtained (abs.) max. pieces of candy allowed if (c_sum > result[2]): result[0] = h_0 result[1] = h_1 result[2] = c_sum break; elif (c_sum < C_max): if (c_sum > result[2]): result[0] = h_0 result[1] = h_1 result[2] = c_sum if (result[2] == C_max): # obtained both (abs.) max pieces of candy allowed and lowest numbered 1st home break return result """ Explanation: Mathematical explanation and Python version as sanity check Let $C_{\text{max}} = $ maximum pieces of candy a child can have (upper bound). The problem stipulated that $0\leq C_{\text{max}} \leq 1000$. Let $N_H = $ total number of homes in the 1 neighborhood. The problem stipulated that $0 < N_H \leq 10000$. Thus, there are $N_H$ homes, ordered consecutively; denote a particular home $h$ s.t. $h\in \lbrace 1,2,\dots N_H\rbrace$. Let $$ \begin{aligned} & c:\lbrace 1,2,\dots N_H \rbrace \to \mathbb{Z}^+ \ & c: h\mapsto c(h) = \text{ number of pieces of candy given at home $h$, i.e. $h$th home } \end{aligned} $$ For some $h_0,h_1$, s.t. $1 \leq h_0 \leq h_1 \leq N_H$, define $c_{\text{tot}}$: $$ c_{\text{tot}} := \sum_{i=h_0}^{h_1} c(i) = c_{\text{tot}}(h_0,h_1,c) $$ i.e. $c_{\text{tot}} : \mathbb{Z}^+ \times \mathbb{Z}^+ \times (\lbrace 1,2,\dots N_H \rbrace \to \mathbb{Z}^+ ) \to \mathbb{Z}^+$. We want to find $$ \max_{ h_0,h_1} c_{\text{tot}}(h_0,h_1,c) $$ with $1 \leq h_0 \leq h_1 \leq N_H$, and if there happened to be more than 1 $h_0$ that yields the maximum amount of candy of all possible (consecutive) sequence of homes from $\lbrace 1,2,\dots N_H \rbrace$, then select the lowest numbered first home $h_0$. This could be denoted (but this prior explanation makes it crystal clear what it means) $$ \min_{h_0} \max_{h_0,h_1} c_{\text{tot}}(h_0,h_1,c) $$ Iterative type algorithm One possible iterative approach could be considered from the following line of thought: Let (initially) $\begin{aligned} & h_{\text{start}} =0 \ & h_{\text{end}} = 0 \ & c_{\text{sum}}=0 \end{aligned}$ Then $\forall \, h_0 \in \lbrace 1,2, \dots N_H \rbrace$, and $\phantom{ \forall \, } \forall \, h_1 \in \lbrace h_0, h_0+1 \dots N_H \rbrace$, consider $c_{\text{tot}}(h_0,h_1,c)$. If $c_{\text{tot}}(h_0,h_1,c) > C_{\text{max}}$, we stop. If $c_{\text{tot}}(h_0,h_1,c) = C_{\text{max}}$ and $c_{\text{tot}}(h_0,h_1,c) > c_{\text{sum}}$, then let $c_{\text{sum}} = c_{\text{tot}}(h_0,h_1,c)$ and stop, since we want the lowest numbered first home. Record the $h_0,h_1$ pair of integers where this occurred, in $h_{\text{start}}, h_{\text{end}}$. If $c_{\text{tot}}(h_0,h_1,c) < C_{\text{max}}$, and if $c_{\text{tot}}(h_0,h_1,c) > c_{\text{sum}}$, then let $c_{\text{sum}} = c_{\text{tot}}(h_0,h_1,c)$. Record the $h_0,h_1$ pair of integers where this occurred, in $h_{\text{start}}, h_{\text{end}}$. We continue. End of explanation """ def main_loop(input_arr): N_H = input_arr[0] C_max = input_arr[1] homes_arr = input_arr[2:] result = np.zeros(3,dtype=int) for h_0 in range(1, N_H +1): c_sum = homes_arr[h_0-1] # be aware of 0-based counting, i.e. counting from 0, of Python and C/C++ if (c_sum > C_max): continue elif (c_sum == C_max): # obtained (abs.) max. pieces of candy allowed if (c_sum > result[2]): result[0] = h_0 result[1] = h_0 result[2] = c_sum break elif (c_sum < C_max): if (c_sum > result[2]): result[0] = h_0 result[1] = h_0 result[2] = c_sum for h_1 in range(h_0+1, N_H +1): c_sum += homes_arr[h_1-1] if (c_sum > C_max): break elif (c_sum == C_max): # obtained (abs.) max. pieces of candy allowed if (c_sum > result[2]): result[0] = h_0 result[1] = h_1 result[2] = c_sum break elif (c_sum < C_max): if (c_sum > result[2]): result[0] = h_0 result[1] = h_1 result[2] = c_sum if (result[2] == C_max): # obtained both (abs.) max pieces of candy allowed and lowest numbered 1st home break return result result_example = main_loop(input_arr) print(result_example, input_arr[2:][result_example[0]-1:result_example[1]] ) %time result_example1 = main_loop(input_arr1) print(result_example1, input_arr1[2:][result_example1[0]-1:result_example1[1]] ) %time result_example2 = main_loop(input_arr2) print(result_example2, input_arr2[2:][result_example2[0]-1:result_example2[1]] ) """ Explanation: We really shouldn't need to do the summation each time. Indeed, notice the relationship: $$ c_{\text{tot}}(h_0,h_1,c) = c_{\text{tot}}(h_0,h_1-1,c) + c(h_1) $$ so that $\forall \, h_0$, keep a "running sum" for the $c$'s. So we have function main_loop, a serial implementation in Python. End of explanation """
myfunprograms/deep_learning
project4/files/dlnd_language_translation_original.ipynb
gpl-3.0
""" DON'T MODIFY ANYTHING IN THIS CELL """ import helper import problem_unittests as tests source_path = 'data/small_vocab_en' target_path = 'data/small_vocab_fr' source_text = helper.load_data(source_path) target_text = helper.load_data(target_path) """ Explanation: Language Translation In this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French. Get the Data Since translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus. End of explanation """ view_sentence_range = (0, 10) """ DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()}))) sentences = source_text.split('\n') word_counts = [len(sentence.split()) for sentence in sentences] print('Number of sentences: {}'.format(len(sentences))) print('Average number of words in a sentence: {}'.format(np.average(word_counts))) print() print('English sentences {} to {}:'.format(*view_sentence_range)) print('\n'.join(source_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]])) print() print('French sentences {} to {}:'.format(*view_sentence_range)) print('\n'.join(target_text.split('\n')[view_sentence_range[0]:view_sentence_range[1]])) """ Explanation: Explore the Data Play around with view_sentence_range to view different parts of the data. End of explanation """ def text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int): """ Convert source and target text to proper word ids :param source_text: String that contains all the source text. :param target_text: String that contains all the target text. :param source_vocab_to_int: Dictionary to go from the source words to an id :param target_vocab_to_int: Dictionary to go from the target words to an id :return: A tuple of lists (source_id_text, target_id_text) """ # TODO: Implement Function return None, None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_text_to_ids(text_to_ids) """ Explanation: Implement Preprocessing Function Text to Word Ids As you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the &lt;EOS&gt; word id at the end of each sentence from target_text. This will help the neural network predict when the sentence should end. You can get the &lt;EOS&gt; word id by doing: python target_vocab_to_int['&lt;EOS&gt;'] You can get other word ids using source_vocab_to_int and target_vocab_to_int. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ helper.preprocess_and_save_data(source_path, target_path, text_to_ids) """ Explanation: Preprocess all the data and save it Running the code cell below will preprocess all the data and save it to file. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np import helper (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess() """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ from distutils.version import LooseVersion import warnings import tensorflow as tf # Check TensorFlow Version assert LooseVersion(tf.__version__) in [LooseVersion('1.0.0'), LooseVersion('1.0.1')], 'This project requires TensorFlow version 1.0 You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) """ Explanation: Check the Version of TensorFlow and Access to GPU This will check to make sure you have the correct version of TensorFlow and access to a GPU End of explanation """ def model_inputs(): """ Create TF Placeholders for input, targets, and learning rate. :return: Tuple (input, targets, learning rate, keep probability) """ # TODO: Implement Function return None, None, None, None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_model_inputs(model_inputs) """ Explanation: Build the Neural Network You'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below: - model_inputs - process_decoding_input - encoding_layer - decoding_layer_train - decoding_layer_infer - decoding_layer - seq2seq_model Input Implement the model_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders: Input text placeholder named "input" using the TF Placeholder name parameter with rank 2. Targets placeholder with rank 2. Learning rate placeholder with rank 0. Keep probability placeholder named "keep_prob" using the TF Placeholder name parameter with rank 0. Return the placeholders in the following the tuple (Input, Targets, Learing Rate, Keep Probability) End of explanation """ def process_decoding_input(target_data, target_vocab_to_int, batch_size): """ Preprocess target data for dencoding :param target_data: Target Placehoder :param target_vocab_to_int: Dictionary to go from the target words to an id :param batch_size: Batch Size :return: Preprocessed target data """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_process_decoding_input(process_decoding_input) """ Explanation: Process Decoding Input Implement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the begining of each batch. End of explanation """ def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob): """ Create encoding layer :param rnn_inputs: Inputs for the RNN :param rnn_size: RNN Size :param num_layers: Number of layers :param keep_prob: Dropout keep probability :return: RNN state """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_encoding_layer(encoding_layer) """ Explanation: Encoding Implement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn(). End of explanation """ def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob): """ Create a decoding layer for training :param encoder_state: Encoder State :param dec_cell: Decoder RNN Cell :param dec_embed_input: Decoder embedded input :param sequence_length: Sequence Length :param decoding_scope: TenorFlow Variable Scope for decoding :param output_fn: Function to apply the output layer :param keep_prob: Dropout keep probability :return: Train Logits """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_decoding_layer_train(decoding_layer_train) """ Explanation: Decoding - Training Create training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs. End of explanation """ def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, vocab_size, decoding_scope, output_fn, keep_prob): """ Create a decoding layer for inference :param encoder_state: Encoder state :param dec_cell: Decoder RNN Cell :param dec_embeddings: Decoder embeddings :param start_of_sequence_id: GO ID :param end_of_sequence_id: EOS Id :param maximum_length: The maximum allowed time steps to decode :param vocab_size: Size of vocabulary :param decoding_scope: TensorFlow Variable Scope for decoding :param output_fn: Function to apply the output layer :param keep_prob: Dropout keep probability :return: Inference Logits """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_decoding_layer_infer(decoding_layer_infer) """ Explanation: Decoding - Inference Create inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder(). End of explanation """ def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob): """ Create decoding layer :param dec_embed_input: Decoder embedded input :param dec_embeddings: Decoder embeddings :param encoder_state: The encoded state :param vocab_size: Size of vocabulary :param sequence_length: Sequence Length :param rnn_size: RNN Size :param num_layers: Number of layers :param target_vocab_to_int: Dictionary to go from the target words to an id :param keep_prob: Dropout keep probability :return: Tuple of (Training Logits, Inference Logits) """ # TODO: Implement Function return None, None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_decoding_layer(decoding_layer) """ Explanation: Build the Decoding Layer Implement decoding_layer() to create a Decoder RNN layer. Create RNN cell for decoding using rnn_size and num_layers. Create the output fuction using lambda to transform it's input, logits, to class logits. Use the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob) function to get the training logits. Use your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, vocab_size, decoding_scope, output_fn, keep_prob) function to get the inference logits. Note: You'll need to use tf.variable_scope to share variables between training and inference. End of explanation """ def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size, enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int): """ Build the Sequence-to-Sequence part of the neural network :param input_data: Input placeholder :param target_data: Target placeholder :param keep_prob: Dropout keep probability placeholder :param batch_size: Batch Size :param sequence_length: Sequence Length :param source_vocab_size: Source vocabulary size :param target_vocab_size: Target vocabulary size :param enc_embedding_size: Decoder embedding size :param dec_embedding_size: Encoder embedding size :param rnn_size: RNN Size :param num_layers: Number of layers :param target_vocab_to_int: Dictionary to go from the target words to an id :return: Tuple of (Training Logits, Inference Logits) """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_seq2seq_model(seq2seq_model) """ Explanation: Build the Neural Network Apply the functions you implemented above to: Apply embedding to the input data for the encoder. Encode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob). Process target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function. Apply embedding to the target data for the decoder. Decode the encoded input using your decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob). End of explanation """ # Number of Epochs epochs = None # Batch Size batch_size = None # RNN Size rnn_size = None # Number of Layers num_layers = None # Embedding Size encoding_embedding_size = None decoding_embedding_size = None # Learning Rate learning_rate = None # Dropout Keep Probability keep_probability = None """ Explanation: Neural Network Training Hyperparameters Tune the following parameters: Set epochs to the number of epochs. Set batch_size to the batch size. Set rnn_size to the size of the RNNs. Set num_layers to the number of layers. Set encoding_embedding_size to the size of the embedding for the encoder. Set decoding_embedding_size to the size of the embedding for the decoder. Set learning_rate to the learning rate. Set keep_probability to the Dropout keep probability End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_path = 'checkpoints/dev' (source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess() max_source_sentence_length = max([len(sentence) for sentence in source_int_text]) train_graph = tf.Graph() with train_graph.as_default(): input_data, targets, lr, keep_prob = model_inputs() sequence_length = tf.placeholder_with_default(max_source_sentence_length, None, name='sequence_length') input_shape = tf.shape(input_data) train_logits, inference_logits = seq2seq_model( tf.reverse(input_data, [-1]), targets, keep_prob, batch_size, sequence_length, len(source_vocab_to_int), len(target_vocab_to_int), encoding_embedding_size, decoding_embedding_size, rnn_size, num_layers, target_vocab_to_int) tf.identity(inference_logits, 'logits') with tf.name_scope("optimization"): # Loss function cost = tf.contrib.seq2seq.sequence_loss( train_logits, targets, tf.ones([input_shape[0], sequence_length])) # Optimizer optimizer = tf.train.AdamOptimizer(lr) # Gradient Clipping gradients = optimizer.compute_gradients(cost) capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None] train_op = optimizer.apply_gradients(capped_gradients) """ Explanation: Build the Graph Build the graph using the neural network you implemented. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import time def get_accuracy(target, logits): """ Calculate accuracy """ max_seq = max(target.shape[1], logits.shape[1]) if max_seq - target.shape[1]: target = np.pad( target, [(0,0),(0,max_seq - target.shape[1])], 'constant') if max_seq - logits.shape[1]: logits = np.pad( logits, [(0,0),(0,max_seq - logits.shape[1]), (0,0)], 'constant') return np.mean(np.equal(target, np.argmax(logits, 2))) train_source = source_int_text[batch_size:] train_target = target_int_text[batch_size:] valid_source = helper.pad_sentence_batch(source_int_text[:batch_size]) valid_target = helper.pad_sentence_batch(target_int_text[:batch_size]) with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(epochs): for batch_i, (source_batch, target_batch) in enumerate( helper.batch_data(train_source, train_target, batch_size)): start_time = time.time() _, loss = sess.run( [train_op, cost], {input_data: source_batch, targets: target_batch, lr: learning_rate, sequence_length: target_batch.shape[1], keep_prob: keep_probability}) batch_train_logits = sess.run( inference_logits, {input_data: source_batch, keep_prob: 1.0}) batch_valid_logits = sess.run( inference_logits, {input_data: valid_source, keep_prob: 1.0}) train_acc = get_accuracy(target_batch, batch_train_logits) valid_acc = get_accuracy(np.array(valid_target), batch_valid_logits) end_time = time.time() print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.3f}, Validation Accuracy: {:>6.3f}, Loss: {:>6.3f}' .format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss)) # Save Model saver = tf.train.Saver() saver.save(sess, save_path) print('Model Trained and Saved') """ Explanation: Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Save parameters for checkpoint helper.save_params(save_path) """ Explanation: Save Parameters Save the batch_size and save_path parameters for inference. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import tensorflow as tf import numpy as np import helper import problem_unittests as tests _, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess() load_path = helper.load_params() """ Explanation: Checkpoint End of explanation """ def sentence_to_seq(sentence, vocab_to_int): """ Convert a sentence to a sequence of ids :param sentence: String :param vocab_to_int: Dictionary to go from the words to an id :return: List of word ids """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_sentence_to_seq(sentence_to_seq) """ Explanation: Sentence to Sequence To feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences. Convert the sentence to lowercase Convert words into ids using vocab_to_int Convert words not in the vocabulary, to the &lt;UNK&gt; word id. End of explanation """ translate_sentence = 'he saw a old yellow truck .' """ DON'T MODIFY ANYTHING IN THIS CELL """ translate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_path + '.meta') loader.restore(sess, load_path) input_data = loaded_graph.get_tensor_by_name('input:0') logits = loaded_graph.get_tensor_by_name('logits:0') keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') translate_logits = sess.run(logits, {input_data: [translate_sentence], keep_prob: 1.0})[0] print('Input') print(' Word Ids: {}'.format([i for i in translate_sentence])) print(' English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence])) print('\nPrediction') print(' Word Ids: {}'.format([i for i in np.argmax(translate_logits, 1)])) print(' French Words: {}'.format([target_int_to_vocab[i] for i in np.argmax(translate_logits, 1)])) """ Explanation: Translate This will translate translate_sentence from English to French. End of explanation """
jpe3002/algorithms-1
elementary-sorting.ipynb
gpl-3.0
import pandas from bokeh.io import push_notebook, show, output_notebook from bokeh.charts import Bar from bokeh.plotting import figure, reset_output import random import time def exch(data, idx_a, idx_b): # todo: fix checking... tmp = data[idx_a] data[idx_a] = data[idx_b] data[idx_b] = tmp def compareTo(a, b): if a > b: return 1 elif a == b: return 0 else: return -1 def less(a, b): return compareTo(a, b) < 0 data = [random.randint(1,100) for c in range(80) ] """ Explanation: Elementary Sorting lecture notes Hur gör man när man sorterar en lista/vektor med element, det är detta som den andra veckan i kursen handlar om. Interface: compareTo(a, b): -1 om b &gt; a, 0 om a = b, 1 om a &gt; b if a not comparable with b: throw exception if a &gt; b: return 1 elif a == b: return 0 else: return -1 less(a, b): return compareTo(a, b) &lt; 0 exch(data[], idx_a, idx_b): if idx_a or idx_b out of range: throw exception tmp = data[idx_a] data[idx_a] = data[idx_b] data[idx_b] = tmp isSorted(data) for idx in range(1, data.length): if data[idx] &lt; data[idx-1]: return False return True End of explanation """ def selection_sort(data): output_notebook() temp = data[:] p = figure(plot_width=400, plot_height=400, title='selection sort') vb = p.vbar(x=[c for c in range(len(temp))], width=0.5, bottom=0, top=temp, color="firebrick") init = p.vbar(x=[c for c in range(len(data))], width=0.5, bottom=0, top=data, color="gray", alpha=0.75) t = show(p, notebook_handle=True) for i in range(len(temp)): min_idx = i for j in range(i+1, len(temp)): if less(temp[j], temp[min_idx]): min_idx = j exch(temp, i, min_idx) push_notebook(handle=t) push_notebook() time.sleep(0.01) reset_output() return temp items = selection_sort(data) """ Explanation: Selection sort: Vi börjar med en naiv sorteringsalgoritm: Ta det första elementet i listan, sök sedan efter det minsta elementet i resterande del av listan. Om ett sådant hittas så byter man plats på det första elementet och detta. Upprepa sedan proceduren för efterföljande element. Denna sorteringsalgoritm har komplexitet: (N-1 + N-2... 1 + 0) == N * N/2... den skalar inte vidare bra. End of explanation """ def insert_sort(data): exchanges = 0 loops = 0 temp = data[:] output_notebook() p = figure(plot_width=400, plot_height=400, title='insert sort') vb = p.vbar(x=[c for c in range(len(temp))], width=0.5, bottom=0, top=temp, color="firebrick") init = p.vbar(x=[c for c in range(len(data))], width=0.5, bottom=0, top=data, color="gray", alpha=0.75) t = show(p, notebook_handle=True) for i in range(len(temp)-1): loops += 1 if less(temp[i+1], temp[i]): exch(temp, i, i+1) push_notebook(handle=t) for j in range(i, 0, -1): loops += 1 if less(temp[j-1], temp[j]): break exch(temp, j-1, j) push_notebook(handle=t) reset_output() return temp #print(''.join(insert_sort(list('SORTEXAMPLE')))) #print(''.join(insert_sort(list('ZYXWVUTSRQPONMLKJIHGFEDCBA')))) #print(''.join(insert_sort(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')))) items = insert_sort(data) """ Explanation: Insertion sort: Vi börjar från början, om efterföljande element mindre än nuvarande element, byt plats på dessa två... (samt fortsätt med jämförelse med tidigare element i listan). Komplexiteten är för denna algoritm i bästa fall i storleksordningen N. Detta inträffar då listan är sorterad. Om listan å andra sidan är "inverterad" så har vi i värsta fall 1 + 2 + 3... + N-2 + N-1 == N * N/2 End of explanation """ def shell_sort(data): N = len(data) temp = data[:] output_notebook() p = figure(plot_width=400, plot_height=400, title='shell sort') vb = p.vbar(x=[c for c in range(N)], width=0.5, bottom=0, top=temp, color="firebrick") init = p.vbar(x=[c for c in range(len(data))], width=0.5, bottom=0, top=data, color="gray", alpha=0.75) t = show(p, notebook_handle=True) h = 1; while h < N//3: h = 3*h + 1 # 1, 4, 13, 40, 121, 364, ... while h >= 1: for i in range(h, N): for j in range(i, h-1, -h): if not less(temp[j], temp[j-h]): break exch(temp, j, j-h) push_notebook(handle=t) time.sleep(0.01) h = h // 3 reset_output() return temp #print(''.join(shell_sort(list('SORTEXAMPLE')))) #print(''.join(shell_sort(list('ZYXWVUTSRQPONMLKJIHGFEDCBA')))) #print(''.join(shell_sort(list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')))) items = shell_sort(data) %%bash ls -l if [ ! -d "reveal.js" ]; then git clone https://github.com/hakimel/reveal.js.git fi if [ -f "elementary-sorting.slides.html" ]; then rm elementary-sorting.slides.html fi %%bash jupyter nbconvert --to slides elementary-sorting.ipynb --reveal-prefix=reveal.js #--post serve """ Explanation: Shellsort: När det gäller shellsort så sorterar man på en större skala först och minskar efter hand intervallen: Intervallen beräknas utifrån hur mycket data man har som skall sorteras. Algoritmen för att räkna ut "intervallen": while h &lt; N // 3: h = 3*h + 1 Detta ger en sekvens med "intervall" 1, 4, 13, 40, 121, 364, ... Sedan tittar vi på alla element "i" mellan h och N, jämför dessa med de element som finns på avståndet "h" mot början av vektorn. Om detta element är mindre än tidigare element (på avstånd h) så byter man plats på dessa, dvs de blir "h sorted"/"h sorterade". När man sedan minskar intervallet mellan elementen så blir sorteringen mer och mer finkorning. Komplexiteten för denna algoritm är i "worst case" N^(3/2), dvs betydligt bättre än "insertion sort" eller "selection sort". End of explanation """
desihub/desimodel
doc/nb/DESI-0347-Updates.ipynb
bsd-3-clause
%pylab inline import os import astropy.table from desimodel.inputs import docdb from desimodel.inputs.throughput import load_spec_throughputs """ Explanation: DESI-347 Throughput Updates to DESIMODEL Study changes to DESIMODEL after updating throughputs from DESI-347. End of explanation """ def compare(old='v13', new='v16'): old_data = os.path.join(os.getenv('DESIMODEL'), 'data.{0}'.format(old)) new_data = os.path.join(os.getenv('DESIMODEL'), 'data.{0}'.format(new)) fig, ax = plt.subplots(2, 1, sharex=True, figsize=(7, 6)) wlen, throughput, extinction, fiberinput = {}, {}, {}, {} for band, color in zip('brz', 'brk'): for version, path, ls in zip((new, old), (new_data, old_data), ('-', ':')): label=f'{version}-{band}' table = astropy.table.Table.read(os.path.join(path, 'throughput', f'thru-{band}.fits'), hdu=1) wlen[label] = np.array(table['wavelength']) throughput[label] = np.asarray(table['throughput']) extinction[label] = np.asarray(table['extinction']) fiberinput[label] = np.asarray(table['fiberinput']) ax[0].plot(wlen[label], throughput[label], ls=ls, c=color, label=label) # Check that only the throughput arrays have changed. assert np.array_equal(wlen[f'{old}-{band}'], wlen[f'{new}-{band}']) assert np.array_equal(extinction[f'{old}-{band}'], extinction[f'{new}-{band}']) assert np.array_equal(fiberinput[f'{old}-{band}'], fiberinput[f'{new}-{band}']) # Plot relative changes in throughput. rel = throughput[f'{new}-{band}'] / throughput[f'{old}-{band}'] ax[1].plot(wlen[label], rel, color=color) # Print integrated throughput in each band. print('| version | b total | r total | z total |') print('|---------|---------|---------|---------|') for version in new, old: print(f'| {version:7s} ', end='') for band in 'brz': label=f'{version}-{band}' total = np.trapz(throughput[label], wlen[label]) print(f'| {total:6.1f}A ', end='') print('|') ax[0].legend(ncol=3) ax[0].set_ylabel('Throughput') ax[1].set_ylabel(f'Relative Change {new}/{old}') ax[1].set_xlabel('Wavelength [A]') ax[1].set_ylim(0.7, 1.3) ax[1].axhline(1, ls='--', c='k') plt.tight_layout() plt.savefig(f'throughput-{new}-{old}.png') compare('v12', 'v13') compare('v13', 'v16') """ Explanation: The code below assumes that $DESIMODEL has subdirectories data.&lt;VERSION&gt; where &lt;VERSION&gt; refers to DESI-347. End of explanation """ def plot_spectro_thru(desi5501_version=3, desi5501_KOSI=True): ccd_thru_file = [] suffix = 'KOSI' if desi5501_KOSI else '' for spectro in range(10): ccd_thru_file.append(docdb.download( 5501, desi5501_version, 'Spectrograph{0}{1}.xlsx'.format(spectro + 1, suffix))) wave, thru = load_spec_throughputs(ccd_thru_file) # Average throughput from row 95 of the Throughput spreadsheet in DESI-0347-v16. wave_avg = [ 350, 360, 375, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 980, 995] thru_avg_v16 = [0.457,0.503,0.577,0.660,0.705,0.660,0.609,0.652,0.690,0.682,0.639,0.796,0.808,0.779,0.449,0.330] # Update for v17 proposed by Pat Jelinsky (16-Apr-2020) thru_avg_v17 = [0.445,0.500,0.585,0.683,0.704,0.652,0.592,0.652,0.690,0.682,0.640,0.796,0.808,0.779,0.449,0.330] # Throughput requirement from IN.SPEC-6004 in DESI-0613. wave_req = [360, 375, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 980] thru_req = [0.21, 0.3, 0.43, 0.55, 0.57, 0.54, 0.50, 0.56, 0.58, 0.56, 0.63, 0.63, 0.62, 0.48] fig = plt.figure(figsize=(8, 5)) #thru_to_avg = [] for spectro in range(10): thru_total = thru[spectro].sum(axis=0) plt.plot(wave, thru_total, ':', label='SM{0:02d}'.format(spectro + 1)) # Interpolate the total throughput onto the wavelength grid used for the average in DESI-347. #thru_to_avg.append(np.interp(wave_avg, wave, thru_total)) plt.fill_between(wave_req, thru_req, 1, color='c', alpha=0.15, lw=1, label='Requirement') plt.plot(wave_avg, thru_avg_v16, 'k+', label='DESI-347-v16') plt.plot(wave_avg, thru_avg_v17, 'ko', label='DESI-347-v17') plt.plot(wave, np.mean(thru.sum(axis=1), axis=0), 'k-', lw=2, alpha=0.75, label='Mean') #plt.plot(wave, np.median(thru.sum(axis=1), axis=0), 'r-', lw=1, label='Median') plt.xlabel('Wavelength [nm]') plt.ylabel('Throughput') plt.ylim(0.3, 0.9) plt.xlim(340, 1000) plt.legend(ncol=3, loc='lower center') plt.grid() plt.tight_layout() plt.savefig('spectro_thru.png') plot_spectro_thru() """ Explanation: Plot the latest per-spectrograph throughputs and compare with the requirements and DESI-0347 coarse grid values: End of explanation """
vitojph/2016progpln
notebooks/8-textblob.ipynb
mit
from textblob import TextBlob """ Explanation: textblob: otro módulo para tareas de PLN (NLTK + pattern) textblob es una librería de procesamiento del texto para Python que permite realizar tareas de Procesamiento del Lenguaje Natural como análisis morfológico, extracción de entidades, análisis de opinión, traducción automática, etc. Está construída sobre otras dos librerías muy famosas de Python: Una ya la conoces: NLTK; la otra es pattern que no vamos a ver en clase porque solo funciona con Python 2, pero si tienes curiosidad, echa un vistazo. La principal ventaja de textblob es que permite combinar el uso de las dos herramientas anteriores en un interfaz más simple. Vamos a apoyarnos en este tutorial para aprender a utilizar algunas de sus funcionalidades más llamativas. Lo primero es importar el objeto TextBlob que nos permite acceder a todas las herramentas que incluye. End of explanation """ texto = '''In new lawsuits brought against the ride-sharing companies Uber and Lyft, the top prosecutors in Los Angeles and San Francisco counties make an important point about the lightly regulated sharing economy. The consumers who participate deserve a very clear picture of the risks they're taking''' t = TextBlob(texto) print('Tenemos', len(t.sentences), 'oraciones.\n') for sentence in t.sentences: print(sentence) """ Explanation: Vamos a crear nuestro primer ejemplo de textblob a través del objeto TextBlob. Piensa en estos textblobs como una especie de cadenas de texto de Python, analaizadas y enriquecidas con algunas características extra. End of explanation """ # imprimimos las oraciones for sentence in t.sentences: print(sentence) print("--------------") # y las palabras print(t.words) print(texto.split()) """ Explanation: Procesando oraciones, palabras y entidades Podemos segmentar en oraciones y en palabras nuestra texto de ejemplo simplemente accediendo a las propiedades .sentences y .words. Imprimimos por pantalla: End of explanation """ print("el texto de ejemplo contiene", len(t.noun_phrases), "entidades") for element in t.noun_phrases: print("-", element) # jugando con lemas, singulares y plurales for word in t.words: if word.endswith("s"): print(word.lemmatize(), word, word.singularize()) else: print(word.lemmatize(), word, word.pluralize()) # ¿cómo podemos hacer la lematización más inteligente? for element in t.tags: # solo lematizamos sustantivos if element[1] == "NN": print(element[0], element[0].lemmatize(), element[0].pluralize() ) elif element[1] == "NNS": print(element[0], element[0].lemmatize(), element[0].singularize()) # y formas verbales if element[1].startswith("VB"): print(element[0], element[0].lemmatize("v")) """ Explanation: La propiedad .noun_phrases nos permite acceder a la lista de entidades (en realidad, son sintagmas nominales) incluídos en nuestro textblob. Así es como funciona. End of explanation """ # análisis sintáctico print(t.parse()) """ Explanation: Análisis sintático Aunque podemos utilizar otros analizadores, por defecto el método .parse() invoca al analizador morfosintáctico del módulo pattern.en que ya conoces. End of explanation """ # de chino a inglés y español oracion_zh = "中国探月工程 亦稱嫦娥工程,是中国启动的第一个探月工程,于2003年3月1日正式启动" t_zh = TextBlob(oracion_zh) print(t_zh.translate(from_lang="zh-CN", to="en")) print(t_zh.translate(from_lang="zh-CN", to="es")) print("--------------") t_es = TextBlob(u"La deuda pública ha marcado nuevos récords en España en el tercer trimestre") print(t_es.translate(to="el")) print(t_es.translate(to="ru")) print(t_es.translate(to="eu")) print(t_es.translate(to="fi")) print(t_es.translate(to="fr")) print(t_es.translate(to="nl")) print(t_es.translate(to="gl")) print(t_es.translate(to="ca")) print(t_es.translate(to="zh")) print(t_es.translate(to="la")) # con el slang no funciona tan bien print("--------------") t_ita = TextBlob("Sono andato a Milano e mi sono divertito un bordello.") print(t_ita.translate(to="en")) print(t_ita.translate(to="es")) """ Explanation: Traducción automática A partir de cualquier texto procesado con TextBlob, podemos acceder a un traductor automático de bastante calidad con el método .translate. Fíjate en cómo lo usamos. Es obligatorio indicar la lengua de destinto. La lengua de origen, se puede predecir a partir del texto de entrada. End of explanation """ # WordNet from textblob import Word from textblob.wordnet import VERB # ¿cuántos synsets tiene "car" word = Word("car") print(word.synsets) # dame los synsets de la palabra "hack" como verbo print(Word("hack").get_synsets(pos=VERB)) # imprime la lista de definiciones de "car" print(Word("car").definitions) # recorre la jerarquía de hiperónimos for s in word.synsets: print(s.hypernym_paths()) """ Explanation: WordNet textblob, más concretamente, cualquier objeto de la clase Word, nos permite acceder a la información de WordNet. End of explanation """ # análisis de opinión opinion1 = TextBlob("This new restaurant is great. I had so much fun!! :-P") print(opinion1.sentiment) opinion2 = TextBlob("Google News to close in Spain.") print(opinion2.sentiment) print(opinion1.sentiment.polarity) if opinion1.sentiment.subjectivity > 0.5: print("Hey, esto es una opinion") """ Explanation: Análisis de opinion End of explanation """ # corrección ortográfica b1 = TextBlob("I havv goood speling!") print(b1.correct()) b2 = TextBlob("Mi naem iz Jonh!") print(b2.correct()) b3 = TextBlob("Boyz dont cri") print(b3.correct()) b4 = TextBlob("psychological posesion achivemen comitment") print(b4.correct()) """ Explanation: Otras curiosidades End of explanation """
james-prior/cohpy
20170706-dojo-clear-to-end-of-table.ipynb
mit
%%script bash # Ignore this boring cell. # It allows one to do C in Jupyter notebook. cat >20170706_head.c <<EOF #include <stdlib.h> #include <stdio.h> #define LINES (3) #define COLUMNS (4) void print_buf(char buf[LINES][COLUMNS]) { for (int row = 0; row < LINES; row++) { for (int column = 0; column < COLUMNS; column++) putchar(buf[row][column]); putchar('\n'); } } EOF cat >20170706_tail.c <<EOF int main(int argc, char *argv()) { char buf[LINES][COLUMNS]; for (int row = 0; row < LINES; row++) for (int column = 0; column < COLUMNS; column++) buf[row][column] = '@'; blank(buf, 1, 2); print_buf(buf); } EOF program_name="${PATH%%:*}/20170706_c_foo" echo $program_name cat >"$program_name" <<EOF #!/usr/bin/env sh cat 20170706_head.c >20170706_blank.c cat >>20170706_blank.c cat 20170706_tail.c >>20170706_blank.c cc 20170706_blank.c -o 20170706_blank ./20170706_blank | tr ' ' '.' EOF chmod +x "$program_name" %%script 20170706_c_foo void blank(char buf[LINES][COLUMNS], int row, int column) { goto MIDDLE; for ( ; row < LINES; row++) for (column = 0; column < COLUMNS; column++) MIDDLE: buf[row][column] = ' '; } """ Explanation: Explores ways of clearing a table, from given starting point to end of line and entire following lines. End of explanation """ %%script 20170706_c_foo void blank(char buf[LINES][COLUMNS], int row, int column) { for ( ; row < LINES; row++) { for ( ; column < COLUMNS; column++) buf[row][column] = ' '; column = 0; } } %%script 20170706_c_foo void blank_to_end_of_row(char buf[LINES][COLUMNS], int row, int column) { for ( ;column < COLUMNS; column++) buf[row][column] = ' '; } void blank_row(char buf[LINES][COLUMNS], int row) { blank_to_end_of_row(buf, row, 0); } void blank(char buf[LINES][COLUMNS], int row, int column) { blank_to_end_of_row(buf, row++, column); for ( ; row < LINES; row++) blank_row(buf, row); } %%script 20170706_c_foo void blank_to_end_of_row(char buf[LINES][COLUMNS], int row, int column) { for ( ;column < COLUMNS; column++) buf[row][column] = ' '; } void blank(char buf[LINES][COLUMNS], int row, int column) { blank_to_end_of_row(buf, row++, column); for ( ; row < LINES; row++) blank_to_end_of_row(buf, row, 0); } """ Explanation: The above is what the output should look like. End of explanation """ LINES = 3 COLUMNS = 4 def foo(row=1, column=2): buf = [ ['@' for _ in range(COLUMNS)] for _ in range(LINES) ] blank(buf, row, column) for row in buf: print(''.join(row).replace(' ', '.')) def blank(buf, row, column): for row in range(row, LINES): for column in range(column, COLUMNS): buf[row][column] = ' ' column = 0 foo() def blank_to_end_of_row(buf, row, column): for column in range(column, COLUMNS): buf[row][column] = ' ' def blank_row(buf, row): blank_to_end_of_row(buf, row, 0) def blank(buf, row, column): blank_to_end_of_row(buf, row, column) row += 1 for row in range(row, LINES): blank_row(buf, row) foo() def blank_to_end_of_row(buf, row, column): for column in range(column, COLUMNS): buf[row][column] = ' ' def blank(buf, row, column): blank_to_end_of_row(buf, row, column) row += 1 for row in range(row, LINES): blank_to_end_of_row(buf, row, 0) foo() %%script 20170706_c_foo /* this is wrong: fails to clear beginning of following lines */ int blank(char buf[LINES][COLUMNS], int row_arg, int column_arg) { int row; int column; for (row = row_arg; row < LINES; row++) for (column = column_arg; column < COLUMNS; column++) buf[row][column] = ' '; } """ Explanation: Now for some Python. End of explanation """
tensorflow/docs-l10n
site/ja/tutorials/distribute/multi_worker_with_keras.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2019 The TensorFlow Authors. End of explanation """ import json import os import sys """ Explanation: Keras を使ったマルチワーカートレーニング <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で実行</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/tutorials/distribute/multi_worker_with_keras.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a></td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/tutorials/distribute/multi_worker_with_keras.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a></td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/tutorials/distribute/multi_worker_with_keras.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a> </td> </table> 概要 このチュートリアルでは、tf.distribute.Strategy API、具体的にはtf.distribute.MultiWorkerMirroredStrategy クラスを使用して、Keras モデルと Model.fit API によるマルチワーカー分散型トレーニングを実演します。このストラテジーの助けにより、シングルワーカーで実行するように設計された Keras モデルは、最小限のコード変更で複数のワーカーでシームレスに機能することができます。 tf.distribute.Strategy API をさらに学習したい方は、TensorFlow での分散トレーニングガイドで TensorFlow がサポートする分散ストラテジーの概要をご覧ください。 Keras とカスタムループで MultiWorkerMirroredStrategy を使用する方法を学習する場合は、Keras と MultiWorkerMirroredStrategy によるカスタムトレーニングループをご覧ください。 このチュートリアルの目的は、2 つのワーカーを使った最小限のマルチワーカーの例を紹介することです。 セットアップ まず、必要なものをインポートします。 End of explanation """ os.environ["CUDA_VISIBLE_DEVICES"] = "-1" """ Explanation: TensorFlow をインポートする前に、環境にいくつかの変更を加えます。 すべての GPU を無効にします。 これにより、すべてのワーカーが同じ GPU を使用しようとすることによって発生するエラーが防止されます。 実際のアプリケーションでは、各ワーカーは異なるマシン上にあります。 End of explanation """ os.environ.pop('TF_CONFIG', None) """ Explanation: TF_CONFIG 環境変数をリセットします(これについては後で詳しく説明します)。 End of explanation """ if '.' not in sys.path: sys.path.insert(0, '.') """ Explanation: 現在のディレクトリが Python のパス上にあることを確認してください。これにより、ノートブックは %%writefile で書き込まれたファイルを後でインポートできるようになります。 End of explanation """ import tensorflow as tf """ Explanation: 次に TensorFlow をインポートします。 End of explanation """ %%writefile mnist_setup.py import os import tensorflow as tf import numpy as np def mnist_dataset(batch_size): (x_train, y_train), _ = tf.keras.datasets.mnist.load_data() # The `x` arrays are in uint8 and have values in the [0, 255] range. # You need to convert them to float32 with values in the [0, 1] range. x_train = x_train / np.float32(255) y_train = y_train.astype(np.int64) train_dataset = tf.data.Dataset.from_tensor_slices( (x_train, y_train)).shuffle(60000).repeat().batch(batch_size) return train_dataset def build_and_compile_cnn_model(): model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(28, 28)), tf.keras.layers.Reshape(target_shape=(28, 28, 1)), tf.keras.layers.Conv2D(32, 3, activation='relu'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) model.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.SGD(learning_rate=0.001), metrics=['accuracy']) return model """ Explanation: データセットとモデルの定義 次に、単純なモデルとデータセットの設定を使用してmnist.pyファイルを作成します。 この Python ファイルは、このチュートリアルのワーカープロセスによって使用されます。 End of explanation """ import mnist_setup batch_size = 64 single_worker_dataset = mnist_setup.mnist_dataset(batch_size) single_worker_model = mnist_setup.build_and_compile_cnn_model() single_worker_model.fit(single_worker_dataset, epochs=3, steps_per_epoch=70) """ Explanation: シングルワーカーでのモデルのトレーニング まず、少数のエポックでモデルをトレーニングし、シングルワーカーで結果を観察して、すべてが正しく機能していることを確認します。エポックが進むにつれ、損失が下降し、精度が 1.0 に近づくはずです。 End of explanation """ tf_config = { 'cluster': { 'worker': ['localhost:12345', 'localhost:23456'] }, 'task': {'type': 'worker', 'index': 0} } """ Explanation: マルチワーカー構成 では、マルチワーカートレーニングの世界を覗いてみましょう。 ジョブとタスクのクラスタ TensorFlow では、分散トレーニングには、いくつかのジョブが含まれる 'cluster' があり、各ジョブには 1 つ以上の 'task' が含まれることがあります。 それぞれに異なる役割をもつ複数のマシンでトレーニングするには TF_CONFIG 環境変数が必要です。TF_CONFIG は JSON 文字列で、クラスタの一部である各ワーカーのクラスタ構成を指定するために使用されます。 TF_CONFIG 変数には、'cluster' と 'task' の 2 つのコンポーネントがあります。 'cluster' はすべてのワーカーに共通し、トレーニングクラスタに関する情報を、'worker' または 'chief' などのさまざまなジョブの種類で構成される dict として提供します。 tf.distribute.MultiWorkerMirroredStrategy によるマルチワーカートレーニングでは通常、'worker' が通常行うことのほかにチェックポイントの保存や TensorBoard 用のサマリーファイルの書き込みといった役割を果たす 1 つの 'worker' があります。こういった 'worker' はチーフワーカー(ジョブ名は 'chief')と呼ばれます。 通例、'chief' には 'index' 0 が指定されます(実際、tf.distribute.Strategy はそのように実装されています)。 'task' は現在のタスクの情報を提供し、ワーカーごとに異なります。タスクはそのワーカーの 'type' と 'index' を指定します。 以下に構成例を示します。 End of explanation """ json.dumps(tf_config) """ Explanation: これは、JSON 文字列としてシリアル化された同じTF_CONFIGです。 End of explanation """ os.environ['GREETINGS'] = 'Hello TensorFlow!' """ Explanation: tf_config は Python 単なるローカル変数です。トレーニング構成で使用するには、この dict を JSON としてシリアル化し、TF_CONFIG 環境変数に配置する必要があります。 上記の構成例では、タスク 'type' を 'worker' に設定し、タスク 'index' を 0 に設定しています。そのため、このマシンが最初のワーカーとなります。'chief' ワーカーとして指定されることになるため、ほかのワーカーよりも多くの作業を行います。 注意: 他のマシンにも TF_CONFIG 環境変数を設定し、同じ 'cluster' dict が必要となりますが、それらのマシンの役割に応じた異なるタスク 'type' またはタスク 'index' が必要となります。 説明の目的により、このチュートリアルではある localhost の 2 つのワーカーでどのようにTF_CONFIG 変数をセットアップできるかを示しています。 実際には、外部 IP aドレス/ポートに複数のワーカーを作成して、ワーカーごとに適宜 TF_CONFIG 変数を設定する必要があります。 このチュートリアルでは、2 つのワーカーを使用します。 最初の ('chief') ワーカーの TF_CONFIG は上記に示す通りです。 2 つ目のワーカーでは、tf_config['task']['index']=1 を設定します。 ノートブックの環境変数とサブプロセス サブプロセスは、親プロセスの環境変数を継承します。 たとえば、この Jupyter ノートブックのプロセスでは、環境変数を次のように設定できます。 End of explanation """ %%bash echo ${GREETINGS} """ Explanation: すると、サブプロセスからその環境変数にアクセスできます。 End of explanation """ strategy = tf.distribute.MultiWorkerMirroredStrategy() """ Explanation: 次のセクションでは、似たような方法で、TF_CONFIG をワーカーのサブプロセスに渡します。実際に行う場合はこのようにしてジョブを起動することはありませんが、この例では十分です。 適切なストラテジーを選択する TensorFlow では、以下の 2 つの分散型トレーニングがあります。 同期トレーニング: トレーニングのステップがワーカーとレプリカ間で同期されます。 非同期トレーニング: トレーニングステップが厳密に同期されません(パラメータサーバートレーニングなど)。 このチュートリアルでは、tf.distribute.MultiWorkerMirroredStrategy のインスタンスを使用して、同期マルチワーカートレーニングを実行する方法を示します。 MultiWorkerMirroredStrategyは、すべてのワーカーの各デバイスにあるモデルのレイヤーにすべての変数のコピーを作成します。集合通信に使用する TensorFlow 演算子CollectiveOpsを使用して勾配を集め、変数の同期を維持します。このストラテジーの詳細は、tf.distribute.Strategyガイドで説明されています。 End of explanation """ with strategy.scope(): # Model building/compiling need to be within `strategy.scope()`. multi_worker_model = mnist_setup.build_and_compile_cnn_model() """ Explanation: 注意: MultiWorkerMirroredStrategyが呼び出されると、TF_CONFIGが解析され、TensorFlow の GRPC サーバーが開始します。そのため、TF_CONFIG環境変数は、tf.distribute.Strategyインスタンスが作成される前に設定しておく必要があります。TF_CONFIGはまだ設定されていないため、上記の戦略は実質的にシングルワーカーのトレーニングです。 MultiWorkerMirroredStrategy は、tf.distribute.experimental.CommunicationOptions パラメータを介して複数の実装を提供します。1) RING は gRPC をクロスホスト通信レイヤーとして使用して、リング状の集合体を実装します。2) NCCL は NVIDIA Collective Communication Library を使用して集合体を実装します。3) AUTO はその選択をランタイムに任せます。集合体の最適な実装は GPU の数と種類、およびクラスタ内のネットワーク相互接続によって異なります。 モデルのトレーニング tf.kerasにtf.distribute.Strategy API を統合したため、トレーニングをマルチワーカーに分散するには、モデルビルディングとmodel.compile()呼び出しをstrategy.scope()内に収めるように変更することだけが必要となりました。この分散ストラテジーのスコープは、どこでどのように変数が作成されるかを指定し、MultiWorkerMirroredStrategyの場合、作成される変数はMirroredVariableで、各ワーカーに複製されます。 End of explanation """ %%writefile main.py import os import json import tensorflow as tf import mnist_setup per_worker_batch_size = 64 tf_config = json.loads(os.environ['TF_CONFIG']) num_workers = len(tf_config['cluster']['worker']) strategy = tf.distribute.MultiWorkerMirroredStrategy() global_batch_size = per_worker_batch_size * num_workers multi_worker_dataset = mnist_setup.mnist_dataset(global_batch_size) with strategy.scope(): # Model building/compiling need to be within `strategy.scope()`. multi_worker_model = mnist_setup.build_and_compile_cnn_model() multi_worker_model.fit(multi_worker_dataset, epochs=3, steps_per_epoch=70) """ Explanation: 注意: 現在のところ、MultiWorkerMirroredStrategy には、TensorFlow 演算子をストラテジーのインスタンスが作成された後に作成する必要があるという制限があります。RuntimeError: Collective ops must be configured at program startup が表示される場合は、プログラムのはじめに MultiWorkerMirroredStrategy のインスタンスを作成するようにし、演算子を作成するコードをストラテジーがインスタンス化される後に配置するようにしてください。 MultiWorkerMirroredStrategyで実際に実行するには、ワーカープロセスを実行し、TF_CONFIGをそれらに渡す必要があります。 前に記述したmnist_setup.pyファイルと同様に、各ワーカーが実行するmain.pyは次のとおりです。 End of explanation """ %%bash ls *.py """ Explanation: 上記のコードスニペットでは、Dataset.batchに渡されるglobal_batch_sizeがper_worker_batch_size * num_workersに設定されていることに注意してください。これにより、ワーカーの数に関係なく、各ワーカーがper_worker_batch_sizeの例のバッチを処理するようになります。 現在のディレクトリには、両方の Python ファイルが含まれています。 End of explanation """ os.environ['TF_CONFIG'] = json.dumps(tf_config) """ Explanation: json はTF_CONFIG}をシリアル化し、環境変数に追加します。 End of explanation """ # first kill any previous runs %killbgscripts %%bash --bg python main.py &> job_0.log """ Explanation: これで、main.pyを実行し、TF_CONFIGを使用するワーカープロセスを起動できます。 End of explanation """ import time time.sleep(10) """ Explanation: 上記のコマンドについて注意すべき点がいくつかあります。 ノートブック 「マジック」 である%%bashを使用して、いくつかの bash コマンドを実行します。 このワーカーは終了しないため、--bgフラグを使用してbashプロセスをバックグラウンドで実行します。 このワーカーは始める前にすべてのワーカーを待ちます。 バックグラウンドのワーカープロセスはこのノートブックに出力を出力しないため、&amp;&gt; で出力をファイルにリダイレクトし、何が起こったかを検査できます。 プロセスが開始するまで数秒待ちます。 End of explanation """ %%bash cat job_0.log """ Explanation: これまでにワーカーのログファイルに出力されたものを検査します。 End of explanation """ tf_config['task']['index'] = 1 os.environ['TF_CONFIG'] = json.dumps(tf_config) """ Explanation: ログファイルの最後の行は Started server with target: grpc://localhost:12345であるはずです。最初のワーカーは準備が整い、他のすべてのワーカーの準備が整うのを待っています。 2番目のワーカーのプロセスを始めるようにtf_configを更新します。 End of explanation """ %%bash python main.py """ Explanation: 2番目のワーカーを起動します。すべてのワーカーがアクティブであるため、これによりトレーニングが開始されます(したがって、このプロセスをバックグラウンドで実行する必要はありません)。 End of explanation """ %%bash cat job_0.log """ Explanation: 最初のワーカーにより書き込まれたログを再確認すると、そのモデルのトレーニングに参加していることがわかります。 End of explanation """ # Delete the `TF_CONFIG`, and kill any background tasks so they don't affect the next section. os.environ.pop('TF_CONFIG', None) %killbgscripts """ Explanation: 当然ながら、これはこのチュートリアルの最初に実行したテストよりも実行速度が劣っています。 単一のマシンで複数のワーカーを実行しても、オーバーヘッドが追加されるだけです。 ここではトレーニングの時間を改善することではなく、マルチワーカートレーニングの例を紹介することを目的としています。 End of explanation """ options = tf.data.Options() options.experimental_distribute.auto_shard_policy = tf.data.experimental.AutoShardPolicy.OFF global_batch_size = 64 multi_worker_dataset = mnist_setup.mnist_dataset(batch_size=64) dataset_no_auto_shard = multi_worker_dataset.with_options(options) """ Explanation: マルチワーカートレーニングの詳細 ここまで、基本的なマルチワーカーのセットアップの実行を見てきました。 このチュートリアルの残りの部分では、実際のユースケースで役立つ重要な要素について詳しく説明します。 データセットのシャーディング マルチワーカートレーニングでは、コンバージェンスとパフォーマンスを確保するために、データセットのシャーディングが必要です。 前のセクションの例は、tf.distribute.Strategy API により提供されるデフォルトの自動シャーディングに依存しています。tf.data.experimental.DistributeOptions の tf.data.experimental.AutoShardPolicy を設定することで、シャーディングを制御できます。 自動シャーディングの詳細については、分散入力ガイドをご覧ください。 自動シャーディングをオフにして、各レプリカがすべての例を処理する方法の簡単な例を次に示します(推奨されません)。 End of explanation """ model_path = '/tmp/keras-model' def _is_chief(task_type, task_id): # Note: there are two possible `TF_CONFIG` configuration. # 1) In addition to `worker` tasks, a `chief` task type is use; # in this case, this function should be modified to # `return task_type == 'chief'`. # 2) Only `worker` task type is used; in this case, worker 0 is # regarded as the chief. The implementation demonstrated here # is for this case. # For the purpose of this Colab section, the `task_type is None` case # is added because it is effectively run with only a single worker. return (task_type == 'worker' and task_id == 0) or task_type is None def _get_temp_dir(dirpath, task_id): base_dirpath = 'workertemp_' + str(task_id) temp_dir = os.path.join(dirpath, base_dirpath) tf.io.gfile.makedirs(temp_dir) return temp_dir def write_filepath(filepath, task_type, task_id): dirpath = os.path.dirname(filepath) base = os.path.basename(filepath) if not _is_chief(task_type, task_id): dirpath = _get_temp_dir(dirpath, task_id) return os.path.join(dirpath, base) task_type, task_id = (strategy.cluster_resolver.task_type, strategy.cluster_resolver.task_id) write_model_path = write_filepath(model_path, task_type, task_id) """ Explanation: 評価 validation_data を Model.fit に渡すと、エポックごとにトレーニングと評価が交互に行われるようになります。validation_data を取る評価は同じセットのワーカー間で分散されているため、評価結果はすべてのワーカーが使用できるように集計されます。 トレーニングと同様に、評価データセットもファイルレベルで自動的にシャーディングされます。評価データセットにグローバルバッチサイズを設定し、validation_steps を設定する必要があります。 評価ではデータセットを繰り返すことも推奨されます。 Alternatively, you can also create another task that periodically reads checkpoints and runs the evaluation. This is what Estimator does. But this is not a recommended way to perform evaluation and thus its details are omitted. 性能 これで、MultiWorkerMirroredStrategy を使ってマルチワーカーで実行するようにセットアップされた Keras モデルの準備ができました。 マルチワーカートレーニングのパフォーマンスを調整するには、次を行うことができます。 tf.distribute.MultiWorkerMirroredStrategy には複数の集合体通信実装が用意されています。 RING は、クロスホスト通信レイヤーとして、gRPC を使用したリング状の集合体を実装します。 NCCL は NVIDIA Collective Communication Library を使用して集合体を実装します。 AUTO は、選択をランタイムに任せます。 集合体の最適な実装は、GPU の数、GPU の種類、およびクラスタ内のネットワーク相互接続によって異なります。自動選択をオーバーライドするには、MultiWorkerMirroredStrategy のコンストラクタの communication_options パラメータを以下のようにして指定します。 python communication_options=tf.distribute.experimental.CommunicationOptions(implementation=tf.distribute.experimental.CollectiveCommunication.NCCL) 可能であれば、変数を tf.float にキャストします。 公式の ResNet モデルには、どのようにしてこれを行うかの例が示されています。 フォールトトレランス 同期トレーニングでは、ワーカーが 1 つでも失敗し、障害復旧の仕組みが存在しない場合、クラスタは失敗します。 Keras をtf.distribute.Strategyで使用する場合、ワーカーが停止した場合や不安定である際に、フォールトトラレンスが機能するというメリットがあります。この機能は、指定された分散ファイルシステムにトレーニングの状態を保存するため、失敗、または、中断されたインスタンスを再開する場合に、トレーニングの状態が復旧されます。 When a worker becomes unavailable, other workers will fail (possibly after a timeout). In such cases, the unavailable worker needs to be restarted, as well as other workers that have failed. 注意: 以前は、ModelCheckpoint コールバックには、マルチワーカートレーニングに失敗したジョブを再開したときに、トレーニングの状態を復元するメカニズムがありました。新たに導入される BackupAndRestore コールバックでは、一貫したエクスペリエンスを提供するために、シングルワーカートレーニングにもこのサポートが追加され、既存の ModelCheckpoint コールバックからフォールトトレランス機能が削除されました。今後、この動作に依存するアプリケーションは、新しい BackupAndRestore コールバックに移行する必要があります。 ModelCheckpoint コールバック ModelCheckpointコールバックは、フォールトトレランス機能を提供しなくなりました。代わりに BackupAndRestoreコールバックを使用してください。 ModelCheckpointコールバックを使用してチェックポイントを保存することは、依然として可能です。ただし、これを使用する場合、トレーニングが中断されるか、問題なく終了した場合、チェックポイントからトレーニングを続行するには、手動でモデルを読み込まなければなりません。 オプションで、ユーザーはModelCheckpointコールバックの外部でモデル/重みを保存および復元することを選択できます。 モデルの保存と読み込み model.save または tf.saved_model.save を使用してモデルを保存するには、ワーカーごとに異なる保存先が必要となります。 チーフワーカー以外のワーカーの場合、モデルを一時ディレクトリに保存する必要があります。 チーフワーカーの場合、指定されたモデルのディレクトリに保存する必要があります。 ワーカーの一時ディレクトリは、複数のワーカーが同じ場所に書き込もうとしてエラーが発生しないように、一意のディレクトリである必要があります。 すべてのディレクトリに保存されるモデルは同一のものであり、復元やサービングで参照されるのは一般的に、チーフワーカーが保存したモデルです。 トレーニングが完了したらワーカーが作成した一時ディレクトリを削除するクリーンアップロジックを用意しておく必要があります。 チーフとワーカーを同時に保存する必要があるのは、チェックポイント中に変数を集計する可能性があり、チーフとワーカーの両方が allreduce 通信プロトコルに参加する必要があるためです。しかしながら、チーフとワーカーを同じモデルディレクトリに保存すると競合が発生し、エラーとなります。 MultiWorkerMirroredStrategy を使用すると、プログラムはワーカーごとに実行され、現在のワーカーがチーフであるかを知る際には、task_type と task_id の属性があるクラスタレゾルバオブジェクトが利用されます。 task_type から、現在のジョブが何であるか('worker' など)を知ることができます。 task_id から、ワーカーの ID を得られます。 task_id == 0 のワーカーはチーフワーカーです。 以下のコードスニペットの write_filepath 関数は、書き込みのファイルパスを指定します。このパスはワーカーの task_id によって異なります。 チーフワーカー(task_id == 0)の場合は、元のファイルパスに書き込みます。 それ以外のワーカーの場合は、書き込むディレクトリパスに task_id を指定して、一時ディレクトリ(temp_dir)を作成します。 End of explanation """ multi_worker_model.save(write_model_path) """ Explanation: これで、保存の準備ができました。 End of explanation """ if not _is_chief(task_type, task_id): tf.io.gfile.rmtree(os.path.dirname(write_model_path)) """ Explanation: 前述したように、後でモデルを読み込む場合、チーフが保存した場所にあるモデルのみを使用するべきなので、非チーフワーカーが保存した一時的なモデルは削除します。 End of explanation """ loaded_model = tf.keras.models.load_model(model_path) # Now that the model is restored, and can continue with the training. loaded_model.fit(single_worker_dataset, epochs=2, steps_per_epoch=20) """ Explanation: 読み込む際に便利な tf.keras.models.load_model API を使用して、以降の作業に続けることにします。 ここでは、単一ワーカーのみを使用してトレーニングを読み込んで続けると仮定します。この場合、別の strategy.scope() 内で tf.keras.models.load_model を呼び出しません(前に定義したように、strategy = tf.distribute.MultiWorkerMirroredStrategy() です)。 End of explanation """ checkpoint_dir = '/tmp/ckpt' checkpoint = tf.train.Checkpoint(model=multi_worker_model) write_checkpoint_dir = write_filepath(checkpoint_dir, task_type, task_id) checkpoint_manager = tf.train.CheckpointManager( checkpoint, directory=write_checkpoint_dir, max_to_keep=1) """ Explanation: チェックポイントの保存と復元 一方、チェックポイントを作成すれば、モデルの重みを保存し、モデル全体を保存せずともそれらを復元することが可能です。 ここでは、モデルをトラッキングする tf.train.Checkpoint を 1 つ作成します。これは tf.train.CheckpointManager によって管理されるため、最新のチェックポイントのみが保存されます。 End of explanation """ checkpoint_manager.save() if not _is_chief(task_type, task_id): tf.io.gfile.rmtree(write_checkpoint_dir) """ Explanation: CheckpointManager の準備ができたら、チェックポイントを保存し、チーフ以外のワーカーが保存したチェックポイントを削除します。 End of explanation """ latest_checkpoint = tf.train.latest_checkpoint(checkpoint_dir) checkpoint.restore(latest_checkpoint) multi_worker_model.fit(multi_worker_dataset, epochs=2, steps_per_epoch=20) """ Explanation: これで、復元する必要があれば、便利なtf.train.latest_checkpoint関数を使用して、保存された最新のチェックポイントを見つけることができるようになりました。チェックポイントが復元されると、トレーニングを続行することができます。 End of explanation """ # Multi-worker training with `MultiWorkerMirroredStrategy` # and the `BackupAndRestore` callback. callbacks = [tf.keras.callbacks.BackupAndRestore(backup_dir='/tmp/backup')] with strategy.scope(): multi_worker_model = mnist_setup.build_and_compile_cnn_model() multi_worker_model.fit(multi_worker_dataset, epochs=3, steps_per_epoch=70, callbacks=callbacks) """ Explanation: BackupAndRestore コールバック tf.keras.callbacks.BackupAndRestore コールバックはフォールトトレランス機能を提供します。この機能はモデルと現在のエポック番号を一時チェックポイントファイルをbackup_dir引数でバックアップし、BackupAndRestoreでコールバックします。これは、各エポックの終了時に実行されます。 ジョブが中断されて再開されると、コールバックは最新のチェックポイントを復元するため、中断されたエポックの始めからトレーニングを続行することができます。未完了のエポックで中断前に実行された部分のトレーニングは破棄されるため、モデルの最終状態に影響することはありません。 これを使用するには、Model.fit 呼び出し時に、 Model.fit のインスタンスを指定します。 MultiWorkerMirroredStrategy では、ワーカーが中断されると、そのワーカーが再開するまでクラスタ全体が一時停止されます。そのワーカーが再開するとほかのワーカーも再開します。中断したワーカーがクラスタに参加し直すと、各ワーカーは以前に保存されたチェックポイントファイルを読み取って以前の状態を復元するため、クラスタの同期状態が戻ります。そして、トレーニングが続行されます。 BackupAndRestore コールバックは、CheckpointManager を使用して、トレーニングの状態を保存・復元します。これには、既存のチェックポイントを最新のものと併せて追跡するチェックポイントと呼ばれるファイルが生成されます。このため、ほかのチェックポイントの保存に backup_dir を再利用しないようにし、名前の競合を回避する必要があります。 現在、BackupAndRestore コールバックは、ストラテジーなしのシングルワーカートレーニング(MirroredStrategy)と MultiWorkerMirroredStrategy によるマルチワーカートレーニングをサポートしています。 以下に、マルチワーカートレーニングとシングルワーカートレーニングの 2 つの例を示します。 End of explanation """
sdpython/teachpyx
_doc/notebooks/python/hypercube.ipynb
mit
from jyquickhelper import add_notebook_menu add_notebook_menu() """ Explanation: Hypercube et autres exercices Exercices autour de tableaux en plusieurs dimensions et autres exercices. End of explanation """ def u(n): if n <= 2: return 1 else: return u(n-1) + u(n-2) + u(n-3) u(5) """ Explanation: Q1 - triple récursivité Réécrire la fonction u de façon à ce qu'elle ne soit plus récurrente. End of explanation """ compteur = [] def u_st(n): global compteur compteur.append(n) if n <= 2: return 1 else: return u_st(n-1) + u_st(n-2) + u_st(n-3) u_st(5), compteur """ Explanation: Le problème de cette écriture est que la fonction est triplement récursive et que son coût est aussi grand que la fonction elle-même. Vérifions. End of explanation """ def u_non_recursif(n): if n <= 2: return 1 u0 = 1 u1 = 1 u2 = 1 i = 3 while i <= n: u = u0 + u1 + u2 u0 = u1 u1 = u2 u2 = u i += 1 return u u_non_recursif(5) """ Explanation: La seconde liste retourne tous les n pour lesquels la fonction u_st a été appelée. End of explanation """ def compare_liste(p, q): i = 0 while i < len(p) and i < len(q): if p [i] < q [i]: return -1 # on peut décider elif p [i] > q [i]: return 1 # on peut décider i += 1 # on ne peut pas décider # fin de la boucle, il faut décider à partir des longueurs des listes if len (p) < len (q): return -1 elif len (p) > len (q): return 1 else : return 0 compare_liste([0, 1], [0, 1, 2]) compare_liste([0, 1, 3], [0, 1, 2]) compare_liste([0, 1, 2], [0, 1, 2]) compare_liste([0, 1, 2, 4], [0, 1, 2]) """ Explanation: Q2 - comparaison de listes On considère deux listes d'entiers. La première est inférieure à la seconde si l'une des deux conditions suivantes est vérifiée : les $n$ premiers nombres sont égaux mais la première liste ne contient que $n$ éléments tandis que la seconde est plus longue, les $n$ premiers nombres sont égaux mais que le $n+1^{\text{ème}}$ de la première liste est inférieur au $n+1^{\text{ème}}$ de la seconde liste Par conséquent, si $l$ est la longueur de la liste la plus courte, comparer ces deux listes d'entiers revient à parcourir tous les indices depuis 0 jusqu'à $l$ exclu et à s'arrêter sur la première différence qui détermine le résultat. S'il n'y pas de différence, alors la liste la plus courte est la première. Il faut écrire une fonction compare_liste(p,q) qui implémente cet algorithme. End of explanation """ def suite_geometrique_1(r): x = 1.0 y = 0.0 n = 0 while x > 0: y += x x *= r n += 1 return y, n print(suite_geometrique_1(0.5)) """ Explanation: Q3 - précision des calculs On cherche à calculer la somme des termes d'une suite géométriques de raison~$\frac{1}{2}$. On définit $r=\frac{1}{2}$, on cherche donc à calculer $\sum_{i=0}^{\infty} r^i$ qui une somme convergente mais infinie. Le programme suivant permet d'en calculer une valeur approchée. Il retourne, outre le résultat, le nombre d'itérations qui ont permis d'estimer le résultat. End of explanation """ def suite_geometrique_2(r): x = 1.0 y = 0.0 n = 0 yold = y + 1 while abs (yold - y) > 0: yold = y y += x x *= r n += 1 return y,n print(suite_geometrique_2(0.5)) """ Explanation: Un informaticien plus expérimenté a écrit le programme suivant qui retourne le même résultat mais avec un nombre d'itérations beaucoup plus petit. End of explanation """ def hyper_cube_liste(n, m=None): if m is None: m = [0, 0] if n > 1 : m[0] = [0,0] m[1] = [0,0] m[0] = hyper_cube_liste (n-1, m[0]) m[1] = hyper_cube_liste (n-1, m[1]) return m hyper_cube_liste(3) """ Explanation: Expliquez pourquoi le second programme est plus rapide tout en retournant le même résultat. Repère numérique : $2^{-55} \sim 2,8.10^{-17}$. Tout d'abord le second programme est plus rapide car il effectue moins d'itérations, 55 au lieu de 1075. Maintenant, il s'agit de savoir pourquoi le second programme retourne le même résultat que le premier mais plus rapidement. L'ordinateur ne peut pas calculer numériquement une somme infinie, il s'agit toujours d'une valeur approchée. L'approximation dépend de la précision des calculs, environ 14 chiffres pour python. Dans le premier programme, on s'arrête lorsque $r^n$ devient nul, autrement dit, on s'arrête lorsque $x$ est si petit que python ne peut plus le représenter autrement que par~0, c'est-à-dire qu'il n'est pas possible de représenter un nombre dans l'intervalle $[0,2^{-1055}]$. Toutefois, il n'est pas indispensable d'aller aussi loin car l'ordinateur n'est de toute façon pas capable d'ajouter un nombre aussi petit à un nombre plus grand que~1. Par exemple, $1 + 10^{17} = 1,000\, 000\, 000\, 000\, 000\, 01$. Comme la précision des calculs n'est que de 15 chiffres, pour python, $1 + 10^{17} = 1$. Le second programme s'inspire de cette remarque : le calcul s'arrête lorsque le résultat de la somme n'évolue plus car il additionne des nombres trop petits à un nombre trop grand. L'idée est donc de comparer la somme d'une itération à l'autre et de s'arrêter lorsqu'elle n'évolue plus. Ce raisonnement n'est pas toujours applicable. Il est valide dans ce cas car la série $s_n = \sum_{i=0}^{n} r^i$ est croissante et positive. Il est valide pour une série convergente de la forme $s_n = \sum_{i=0}^{n} u_i$ et une suite $u_n$ de module décroissant. Q4 - hypercube Un chercheur cherche à vérifier qu'une suite de~0 et de~1 est aléatoire. Pour cela, il souhaite compter le nombre de séquences de $n$ nombres successifs. Par exemple, pour la suite 01100111 et $n=3$, les triplets sont 011, 110, 100, 001, 011, 111. Le triplet 011 apparaît deux fois, les autres une fois. Si la suite est aléatoire, les occurrences de chaque triplet sont en nombres équivalents. End of explanation """ def hyper_cube_dico (n) : r = { } ind = [ 0 for i in range (0,n) ] while ind [0] <= 1 : cle = tuple(ind) # conversion d'une liste en tuple r[cle] = 0 ind[-1] += 1 k = len(ind)-1 while ind[k] == 2 and k > 0: ind[k] = 0 ind[k-1] += 1 k -= 1 return r hyper_cube_dico(3) """ Explanation: La seconde à base de dictionnaire (plus facile à manipuler) : End of explanation """ def occurrence(l,n) : # d = ....... # choix d'un hyper_cube (n) # ..... # return d pass suite = [ 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1 ] h = occurrence(suite, 3) h """ Explanation: Le chercheur a commencé à écrire son programme : End of explanation """ def occurrence(tu, n): d = hyper_cube_dico(n) for i in range (0, len(tu)-n) : cle = tu[i:i+n] d[cle] += 1 return d occurrence((1, 0, 1, 1, 0, 1, 0), 3) """ Explanation: Sur quelle structure se porte votre choix (a priori celle avec dictionnaire), compléter la fonction occurrence. End of explanation """ def occurrence2(tu, n): d = { } for i in range (0, len(tu)-n) : cle = tu[i:i+n] if cle not in d: d[cle] = 0 d [cle] += 1 return d occurrence2((1, 0, 1, 1, 0, 1, 0), 3) """ Explanation: Il est même possible de se passer de la fonction hyper_cube_dico : End of explanation """ def occurrence3(li, n): d = hyper_cube_liste(n) for i in range (0, len(li)-n) : cle = li[i:i+n] t = d # for k in range (0,n-1) : # point clé de la fonction : t = t[cle[k]] # accès à un élément t [cle [ n-1] ] += 1 return d occurrence3((1, 0, 1, 1, 0, 1, 0), 3) """ Explanation: La seule différence apparaît lorsqu'un n-uplet n'apparaît pas dans la liste. Avec la fonction hyper_cube_dico, ce n-uplet recevra la fréquence 0, sans cette fonction, ce n-uplet ne sera pas présent dans le dictionnaire d. Le même programme avec la structure matricielle est plus une curiosité qu'un cas utile. End of explanation """ def hyper_cube_liste2(n, m=[0, 0], m2=[0, 0]): if n > 1 : m[0] = list(m2) m[1] = list(m2) m[0] = hyper_cube_liste2(n-1, m[0]) m[1] = hyper_cube_liste2(n-1, m[1]) return m def occurrence4(li, n): d = hyper_cube_liste2(n) # * remarque voir plus bas for i in range (0, len(li)-n) : cle = li[i:i+n] t = d # for k in range (0,n-1) : # point clé de la fonction : t = t[cle[k]] # accès à un élément t [cle [ n-1] ] += 1 return d occurrence4((1, 0, 1, 1, 0, 1, 0), 3) """ Explanation: Une autre écriture... End of explanation """ def hyper_cube_liste3(n, m=[0, 0], m2=[0, 0]): if n > 1 : m[0] = m2 m[1] = m2 m[0] = hyper_cube_liste3(n-1, m[0]) m[1] = hyper_cube_liste3(n-1, m[1]) return m def occurrence5(li, n): d = hyper_cube_liste3(n) # * remarque voir plus bas for i in range (0, len(li)-n) : cle = li[i:i+n] t = d # for k in range (0,n-1) : # point clé de la fonction : t = t[cle[k]] # accès à un élément t [cle [ n-1] ] += 1 return d try: occurrence5((1, 0, 1, 1, 0, 1, 0), 3) except Exception as e: print(e) """ Explanation: Et si on remplace list(m2) par m2. End of explanation """
turbomanage/training-data-analyst
courses/machine_learning/deepdive2/launching_into_ml/solutions/repeatable_splitting.ipynb
apache-2.0
from google.cloud import bigquery """ Explanation: <h1> Repeatable splitting </h1> In this notebook, we will explore the impact of different ways of creating machine learning datasets. <p> Repeatability is important in machine learning. If you do the same thing now and 5 minutes from now and get different answers, then it makes experimentation difficult. In other words, you will find it difficult to gauge whether a change you made has resulted in an improvement or not. End of explanation """ compute_alpha = """ #standardSQL SELECT SAFE_DIVIDE( SUM(arrival_delay * departure_delay), SUM(departure_delay * departure_delay)) AS alpha FROM ( SELECT RAND() AS splitfield, arrival_delay, departure_delay FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' ) WHERE splitfield < 0.8 """ results = bigquery.Client().query(compute_alpha).to_dataframe() alpha = results['alpha'][0] print(alpha) """ Explanation: <h3> Create a simple machine learning model </h3> The dataset that we will use is <a href="https://bigquery.cloud.google.com/table/bigquery-samples:airline_ontime_data.flights">a BigQuery public dataset</a> of airline arrival data. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is 70 million, and then switch to the Preview tab to look at a few rows. <p> We want to predict the arrival delay of an airline based on the departure delay. The model that we will use is a zero-bias linear model: $$ delay_{arrival} = \alpha * delay_{departure} $$ <p> To train the model is to estimate a good value for $\alpha$. <p> One approach to estimate alpha is to use this formula: $$ \alpha = \frac{\sum delay_{departure} delay_{arrival} }{ \sum delay_{departure}^2 } $$ Because we'd like to capture the idea that this relationship is different for flights from New York to Los Angeles vs. flights from Austin to Indianapolis (shorter flight, less busy airports), we'd compute a different $alpha$ for each airport-pair. For simplicity, we'll do this model only for flights between Denver and Los Angeles. <h2> Naive random split (not repeatable) </h2> End of explanation """ compute_rmse = """ #standardSQL SELECT dataset, SQRT( AVG( (arrival_delay - ALPHA * departure_delay) * (arrival_delay - ALPHA * departure_delay) ) ) AS rmse, COUNT(arrival_delay) AS num_flights FROM ( SELECT IF (RAND() < 0.8, 'train', 'eval') AS dataset, arrival_delay, departure_delay FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' ) GROUP BY dataset """ bigquery.Client().query( compute_rmse.replace('ALPHA', str(alpha))).to_dataframe() """ Explanation: <h3> What is wrong with calculating RMSE on the training and test data as follows? </h3> End of explanation """ train_and_eval_rand = """ #standardSQL WITH alldata AS ( SELECT IF (RAND() < 0.8, 'train', 'eval') AS dataset, arrival_delay, departure_delay FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' ), training AS ( SELECT SAFE_DIVIDE( SUM(arrival_delay * departure_delay), SUM(departure_delay * departure_delay)) AS alpha FROM alldata WHERE dataset = 'train' ) SELECT MAX(alpha) AS alpha, dataset, SQRT( AVG( (arrival_delay - alpha * departure_delay) * (arrival_delay - alpha * departure_delay) ) ) AS rmse, COUNT(arrival_delay) AS num_flights FROM alldata, training GROUP BY dataset """ bigquery.Client().query(train_and_eval_rand).to_dataframe() """ Explanation: Hint: * Are you really getting the same training data in the compute_rmse query as in the compute_alpha query? * Do you get the same answers each time you rerun the compute_alpha and compute_rmse blocks? <h3> How do we correctly train and evaluate? </h3> <br/> Here's the right way to compute the RMSE using the actual training and held-out (evaluation) data. Note how much harder this feels. Although the calculations are now correct, the experiment is still not repeatable. Try running it several times; do you get the same answer? End of explanation """ compute_alpha = """ #standardSQL SELECT SAFE_DIVIDE( SUM(arrival_delay * departure_delay), SUM(departure_delay * departure_delay)) AS alpha FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' AND ABS(MOD(FARM_FINGERPRINT(date), 10)) < 8 """ results = bigquery.Client().query(compute_alpha).to_dataframe() alpha = results['alpha'][0] print(alpha) """ Explanation: <h2> Using HASH of date to split the data </h2> Let's split by date and train. End of explanation """ compute_rmse = """ #standardSQL SELECT IF(ABS(MOD(FARM_FINGERPRINT(date), 10)) < 8, 'train', 'eval') AS dataset, SQRT( AVG( (arrival_delay - ALPHA * departure_delay) * (arrival_delay - ALPHA * departure_delay) ) ) AS rmse, COUNT(arrival_delay) AS num_flights FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' GROUP BY dataset """ print(bigquery.Client().query( compute_rmse.replace('ALPHA', str(alpha))).to_dataframe().head()) """ Explanation: We can now use the alpha to compute RMSE. Because the alpha value is repeatable, we don't need to worry that the alpha in the compute_rmse will be different from the alpha computed in the compute_alpha. End of explanation """
ContextLab/quail
docs/tutorial/naturalistic-analyses.ipynb
mit
import quail import numpy as np import seaborn as sns from scipy.spatial.distance import cdist %matplotlib inline egg = quail.load_example_data(dataset='naturalistic') """ Explanation: Analyzing naturalistic stimuli In traditional list-learning free recall experiments, remembering is often cast as a binary operation: either an item is recalled or it isn't. This allows for a straight forward matching between the presented and recalled stimuli. However, characterizing and evaluating memory in more realistic contexts (e.g., telling a story to a friend about a recent vacation) is much more nuanced. Real-world recall is continuous, rather than binary. Further, the specific words used to describe an experience may vary considerably across participants. To handle this new data regime, we extended classic methods developed for free-recall list-learning experiments to accomodate naturalistic stimuli. Specifically, we provide a more flexible 'matching function', which quantifies the similarity between stimuli and verbal responses in a continuous manner. In the tutorial below, we will describe our new analysis approach and demonstrate how to perform the analyses using quail. To get started, let's load in the example data: End of explanation """ egg.info() """ Explanation: The example data used in this tutorial is based on an open dataset from Chen et al., 2017, in which 17 participants viewed and then verbally recounted an episode of the BBC series Sherlock. We fit a topic model to hand-annotated text descriptions of the episode and used the model to transform the video annotations and the recall transcriptions for each subject. We then used a Hidden Markov Model to segment the video and recall models into an (optimal) number of events. The result was a matrix of topic vectors representing the "events" in the video and list of matrices of topic vectors representing participant's recall "events". We created an egg from these vector representations of the stimulus and verbal recall, where the topic vectors were passed to quail as a stimulus features. Let's take a closer look at the egg: End of explanation """ # The label of each stimulus event... egg.get_pres_items().head() # ...and their corresponding topic vectors egg.get_pres_features().head() # a closer look at one of the dictionaries egg.get_pres_features()[0][0][0] """ Explanation: Here, the egg's pres field consists of 34 stimulus events (the number of video segments determined by our HMM). Each stimulus event is represented by a dictionary containing the label of the video segment (item) and a topic vector representing that event (topics). End of explanation """ # The temporal position of each recall event... egg.get_rec_items().head() # ...and their corresponding topic vectors egg.get_rec_features().head() """ Explanation: As you can see above, the dictionary contains a features key, which holds a 100D topic vector representing a stimulus event and also a temporal key, which describes the serial position of the stimulus. The rec field contains the recall events for each subject, similarly represented by a label ('item') and topic vectors it comprises ('topics'). End of explanation """ pres_mtx = np.array([x['topics'] for x in egg.get_pres_features('topics').iloc[0, :].values]) sns.heatmap(pres_mtx, vmin=0, vmax=1) """ Explanation: Defining a matching function As summarized above, quail supports the analysis of naturalistic stimuli by providing a more flexible way to match presented stimuli and recall responses. The matching function can be set using the match keyword argument in egg.analyze. There are three options: 'exact', 'best', and 'smooth'. If match='exact', the recall item must be identical to the stimulus to constitute a recall. This is the traditional approach for free recall experiments (either a subject accurately recalled the stimulus item, or did not) but it is not particularly useful with naturalistic data. For the naturalistic options, quail computes a similarity matrix comparing every recall event to every stimulus event. If match='best', the recall response that is most similar to a given presented stimulus is labeled as recalled. If match='smooth', a weighted-average over recall responses is computed for each presented stimulus, where the weights are derived from the similarity between the stimulus and the recall event. To illustrate this further, let's step through the analysis. First, let's create a matrix representing the presented stimulus where each row is an 'event' and each column is a topic dimension: End of explanation """ rec_mtx = np.array([x['topics'] for x in egg.get_rec_features('topics').iloc[12, :].values if len(x)]) sns.heatmap(rec_mtx, vmin=0, vmax=1) """ Explanation: We'll also create a matrix representing the recalled events for a single subject: End of explanation """ match_mtx = 1 - cdist(pres_mtx, rec_mtx, 'correlation') sns.heatmap(match_mtx, vmin=0, vmax=1) """ Explanation: To measure similarity between the pres_mtx and rec_mtx along this feature dimension, we can use the cdist function from scipy. In this example, we will use correlational distance to measure similarity between each presented event and each recalled event: End of explanation """ np.argmax(match_mtx, 0) """ Explanation: This matrix quantifies the match between each presented stimulus and each recalled stimulus. The light stripe along the diagonal suggests that this particular subject remembered most of the events in order, since the highest correlation values are roughly along the diagonal. Matching with 'best' If match='best', each recall event is mapped to the single stimulus event with the most similar feature vector: End of explanation """ spc = egg.analyze(analysis='spc', match='best', distance='correlation', features=['topics']) spc.get_data().head() """ Explanation: Note that once the data is distilled into this form, many of the classic list-learning analyses (such as probability of first recall, serial position curve, and lag-conditional response probability curve) can be performed. To do this using quail, simply set match='best', choose a distance function (euclidean by default) and select the features that you would like to use (e.g. features=['topics']). End of explanation """ spc.plot() """ Explanation: Each stimulus event is assigned a binary value for each recall event – it either was matched or it was not. To plot it: End of explanation """ spc = egg.analyze(analysis='spc', match='smooth', distance='correlation', features=['topics']) spc.data.head() spc.plot() """ Explanation: Matching with 'smooth' if match='smooth', quail computes a weighted average across all stimulus events for each recall event, where the weights are derived from similarity between the stimulus and recall. End of explanation """ spc = egg.analyze(analysis='spc', match='smooth', distance='cosine', features=['topics']) spc.plot() """ Explanation: Changing the distance metric The distance argument assigns the distance function quail will use to compute similarity between stimulus and recall events. We support any distance metric included in scipy.spatial.distance.cdist: End of explanation """
bobmyhill/burnman
tutorial/tutorial_04_fitting.ipynb
gpl-2.0
import burnman import numpy as np import matplotlib.pyplot as plt """ Explanation: <h1>The BurnMan Tutorial</h1> Part 4: Fitting This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for the Earth and Planetary Sciences Copyright (C) 2012 - 2021 by the BurnMan team, released under the GNU GPL v2 or later. Introduction This ipython notebook is the fourth in a series designed to introduce new users to the code structure and functionalities present in BurnMan. <b>Demonstrates</b> burnman.optimize.eos_fitting.fit_PTV_data burnman.optimize.composition_fitting.fit_composition_to_solution burnman.optimize.composition_fitting.fit_phase_proportions_to_bulk_composition Everything in BurnMan and in this tutorial is defined in SI units. End of explanation """ PV = np.array([[0.0001, 46.5126, 0.0061], [1.168, 46.3429, 0.0053], [2.299, 46.1756, 0.0043], [3.137, 46.0550, 0.0051], [4.252, 45.8969, 0.0045], [5.037, 45.7902, 0.0053], [5.851, 45.6721, 0.0038], [6.613, 45.5715, 0.0050], [7.504, 45.4536, 0.0041], [8.264, 45.3609, 0.0056], [9.635, 45.1885, 0.0042], [11.69, 44.947, 0.002], [17.67, 44.264, 0.002], [22.38, 43.776, 0.003], [29.38, 43.073, 0.009], [37.71, 42.278, 0.008], [46.03, 41.544, 0.017], [52.73, 40.999, 0.009], [26.32, 43.164, 0.006], [30.98, 42.772, 0.005], [34.21, 42.407, 0.003], [38.45, 42.093, 0.004], [43.37, 41.610, 0.004], [47.49, 41.280, 0.007]]) print(f'{len(PV)} data points loaded successfully.') """ Explanation: Fitting parameters for an equation of state to experimental data BurnMan contains least-squares optimization functions that fit model parameters to data. There are two helper functions especially for use in fitting Mineral parameters to experimental data; these are burnman.optimize.eos_fitting.fit_PTp_data (which can fit multiple kinds of data at the same time), and burnman.optimize.eos_fitting.fit_PTV_data, which specifically fits only pressure-temperature-volume data. An extended example of fitting various kinds of data, outlier removal and detailed analysis can be found in examples/example_fit_eos.py. In this tutorial, we shall focus solely on fitting room temperature pressure-temperature-volume data. Specifically, the data we will fit is experimental volumes of stishovite, taken from Andrault et al. (2003). This data is provided in the form [P (GPa), V (Angstrom^3) and sigma_V (Angstrom^3)]. End of explanation """ from burnman.tools.unitcell import molar_volume_from_unit_cell_volume Z = 2. # number of formula units per unit cell in stishovite PTV = np.array([PV[:,0]*1.e9, 298.15 * np.ones_like(PV[:,0]), molar_volume_from_unit_cell_volume(PV[:,1], Z)]).T # Here, we assume that the pressure uncertainties are equal to 3% of the total pressure, # that the temperature uncertainties are negligible, and take the unit cell volume # uncertainties from the paper. # We also assume that the uncertainties in pressure and volume are uncorrelated. nul = np.zeros_like(PTV[:,0]) PTV_covariances = np.array([[0.03*PTV[:,0], nul, nul], [nul, nul, nul], [nul, nul, molar_volume_from_unit_cell_volume(PV[:,2], Z)]]).T PTV_covariances = np.power(PTV_covariances, 2.) """ Explanation: BurnMan works exclusively in SI units, so we have to convert from GPa to Pa, and Angstrom per cell into molar volume in m^3. The fitting function also takes covariance matrices as input, so we have to build those matrices. End of explanation """ stv = burnman.minerals.HP_2011_ds62.stv() params = ['V_0', 'K_0', 'Kprime_0'] fitted_eos = burnman.optimize.eos_fitting.fit_PTV_data(stv, params, PTV, PTV_covariances, verbose=False) print('Optimized equation of state for stishovite:') burnman.tools.misc.pretty_print_values(fitted_eos.popt, fitted_eos.pcov, fitted_eos.fit_params) print('') """ Explanation: The next code block creates a Mineral object (stv), providing starting guesses for the parameters. The user selects which parameters they wish to fit, and which they wish to keep fixed. The parameters of the Mineral object are automatically updated during fitting. Finally, the optimized parameter values and their variances are printed to screen. End of explanation """ import matplotlib matplotlib.rc('axes.formatter', useoffset=False) # turns offset off, makes for a more readable plot fig = burnman.nonlinear_fitting.corner_plot(fitted_eos.popt, fitted_eos.pcov, params) axes = fig[1] axes[1][0].set_xlabel('$V_0$ ($\\times 10^{-5}$ m$^3$)') axes[1][1].set_xlabel('$K_0$ ($\\times 10^{11}$ Pa)') axes[0][0].set_ylabel('$K_0$ ($\\times 10^{11}$ Pa)') axes[1][0].set_ylabel('$K\'_0$') plt.show() """ Explanation: The fitted_eos object contains a lot of useful information about the fit. In the next code block, we fit the corner plot of the covariances, showing the tradeoffs in different parameters. End of explanation """ from burnman.tools.misc import attribute_function from burnman.optimize.nonlinear_fitting import confidence_prediction_bands T = 298.15 pressures = np.linspace(1.e5, 60.e9, 101) temperatures = T*np.ones_like(pressures) volumes = stv.evaluate(['V'], pressures, temperatures)[0] PTVs = np.array([pressures, temperatures, volumes]).T # Calculate the 95% confidence and prediction bands cp_bands = confidence_prediction_bands(model=fitted_eos, x_array=PTVs, confidence_interval=0.95, f=attribute_function(stv, 'V'), flag='V') plt.fill_between(pressures/1.e9, cp_bands[2] * 1.e6, cp_bands[3] * 1.e6, color=[0.75, 0.25, 0.55], label='95% prediction bands') plt.fill_between(pressures/1.e9, cp_bands[0] * 1.e6, cp_bands[1] * 1.e6, color=[0.75, 0.95, 0.95], label='95% confidence bands') plt.plot(PTVs[:,0] / 1.e9, PTVs[:,2] * 1.e6, label='Optimized fit for stishovite') plt.errorbar(PTV[:,0] / 1.e9, PTV[:,2] * 1.e6, xerr=np.sqrt(PTV_covariances[:,0,0]) / 1.e9, yerr=np.sqrt(PTV_covariances[:,2,2]) * 1.e6, linestyle='None', marker='o', label='Andrault et al. (2003)') plt.ylabel("Volume (cm$^3$/mol)") plt.xlabel("Pressure (GPa)") plt.legend(loc="upper right") plt.title("Stishovite EoS (room temperature)") plt.show() """ Explanation: We now plot our optimized equation of state against the original data. BurnMan also includes a useful function burnman.optimize.nonlinear_fitting.confidence_prediction_bands that can be used to calculate the nth percentile confidence and prediction bounds on a function given a model using the delta method. End of explanation """ cp_bands = confidence_prediction_bands(model=fitted_eos, x_array=PTVs, confidence_interval=0.95, f=attribute_function(stv, 'K_T'), flag='V') plt.fill_between(pressures/1.e9, (cp_bands[0])/1.e9, (cp_bands[1])/1.e9, color=[0.75, 0.95, 0.95], label='95% confidence band') plt.plot(pressures/1.e9, (cp_bands[0] + cp_bands[1])/2.e9, color='b', label='Best fit') plt.ylabel("Bulk modulus (GPa)") plt.xlabel("Pressure (GPa)") plt.legend(loc="upper right") plt.title("Stishovite EoS; uncertainty in bulk modulus (room temperature)") plt.show() """ Explanation: We can also calculate the confidence and prediction bands for any other property of the mineral. In the code block below, we calculate and plot the optimized isothermal bulk modulus and its uncertainties. End of explanation """ from burnman import minerals gt = minerals.JH_2015.garnet() print(f'Endmembers: {gt.endmember_names}') print(f'Elements: {gt.elements}') print('Stoichiometric matrix:') print(gt.stoichiometric_matrix) """ Explanation: Finding the best fit endmember proportions of a solution given a bulk composition Let's now turn our focus to a different kind of fitting. It is common in petrology to have a bulk composition of a phase (provided, for example, by electron probe microanalysis), and want to turn this composition into a formula that satisfies stoichiometric constraints. This can be formulated as a constrained, weighted least squares problem, and BurnMan can be used to solve these problems using the function burnman.optimize.composition_fitting.fit_composition_to_solution. In the following example, we shall create a model garnet composition, and then fit that to the Jennings and Holland (2015) garnet solution model. First, let's look at the solution model endmembers (pyrope, almandine, grossular, andradite and knorringite): End of explanation """ fitted_variables = ['Fe', 'Ca', 'Mg', 'Cr', 'Al', 'Si', 'Fe3+'] variable_values = np.array([1.1, 2., 0., 0, 1.9, 3., 0.1]) variable_covariances = np.eye(7)*0.01*0.01 # Add some noise. v_err = np.random.rand(7) np.random.seed(100) variable_values = np.random.multivariate_normal(variable_values, variable_covariances) """ Explanation: Now, let's create a model garnet composition. A unique composition can be determined with the species Fe (total), Ca, Mg, Cr, Al, Si and Fe3+, all given in mole amounts. On top of this, we add some random noise (using a fixed seed so that the composition is reproducible). End of explanation """ variable_conversions = {'Fe3+': {'Fef_B': 1.}} """ Explanation: Importantly, Fe3+ isn't an element or a site-species of the solution model, so we need to provide the linear conversion from Fe3+ to elements and/or site species. In this case, Fe3+ resides only on the second site (Site B), and the JH_2015.gt model has labelled Fe3+ on that site as Fef. Therefore, the conversion is simply Fe3+ = Fef_B. End of explanation """ from burnman.optimize.composition_fitting import fit_composition_to_solution popt, pcov, res = fit_composition_to_solution(gt, fitted_variables, variable_values, variable_covariances, variable_conversions) """ Explanation: Now we're ready to do the fitting. The following line is all that is required, and yields as output the optimized parameters, the corresponding covariance matrix and the residual. End of explanation """ # We can set the composition of gt using the optimized parameters gt.set_composition(popt) # Print the optimized parameters and principal uncertainties print('Molar fractions:') for i in range(len(popt)): print(f'{gt.endmember_names[i]}: ' f'{gt.molar_fractions[i]:.3f} +/- ' f'{np.sqrt(pcov[i][i]):.3f}') print(f'Weighted residual: {res:.3f}') """ Explanation: Finally, the optimized parameters can be used to set the composition of the solution model, and the optimized parameters printed to stdout. End of explanation """ fig = burnman.nonlinear_fitting.corner_plot(popt, pcov, gt.endmember_names) """ Explanation: As in the equation of state fitting, a corner plot of the covariances can also be plotted. End of explanation """ import itertools # Load and transpose input data filename = '../burnman/data/input_fitting/Bertka_Fei_1997_mars_mantle.dat' with open(filename) as f: column_names = f.readline().strip().split()[1:] data = np.genfromtxt(filename, dtype=None, encoding='utf8') data = list(map(list, itertools.zip_longest(*data, fillvalue=None))) # The first six columns are compositions given in weight % oxides compositions = np.array(data[:6]) # The first row is the bulk composition bulk_composition = compositions[:, 0] # Load all the data into a dictionary data = {column_names[i]: np.array(data[i]) for i in range(len(column_names))} # Make ordered lists of samples (i.e. experiment ID) and phases samples = [] phases = [] for i in range(len(data['sample'])): if data['sample'][i] not in samples: samples.append(data['sample'][i]) if data['phase'][i] not in phases: phases.append(data['phase'][i]) samples.remove("bulk_composition") phases.remove("bulk") # Get the indices of all the phases present in each sample sample_indices = [[i for i in range(len(data['sample'])) if data['sample'][i] == sample] for sample in samples] # Get the run pressures of each experiment pressures = np.array([data['pressure'][indices[0]] for indices in sample_indices]) """ Explanation: Fitting phase proportions to a bulk composition Another common constrained weighted least squares problem involves fitting phase proportions, given their individual compositions and the overall bulk composition. This is particularly important in experimental petrology, where the bulk composition is known from a starting composition. In these cases, the residual after fitting is often used to assess whether the sample remained a closed system during the experiment. In the following example, we take phase compositions and the bulk composition reported from high pressure experiments on a Martian mantle composition by Bertka and Fei (1997), and use these to calculate phase proportions in Mars mantle, and the quality of the experiments. First, some tedious data preparation... End of explanation """ from burnman.optimize.composition_fitting import fit_phase_proportions_to_bulk_composition # Create empty arrays to store the weight proportions of each phase, # and the principal uncertainties (we do not use the covariances here, # although they are calculated) weight_proportions = np.zeros((len(samples), len(phases)))*np.NaN weight_proportion_uncertainties = np.zeros((len(samples), len(phases)))*np.NaN residuals = [] # Loop over the samples, fitting phase proportions # to the provided bulk composition for i, sample in enumerate(samples): # This line does the heavy lifting popt, pcov, res = fit_phase_proportions_to_bulk_composition(compositions[:, sample_indices[i]], bulk_composition) residuals.append(res) # Fill the correct elements of the weight_proportions # and weight_proportion_uncertainties arrays sample_phases = [data['phase'][i] for i in sample_indices[i]] for j, phase in enumerate(sample_phases): weight_proportions[i, phases.index(phase)] = popt[j] weight_proportion_uncertainties[i, phases.index(phase)] = np.sqrt(pcov[j][j]) """ Explanation: The following code block loops over each of the compositions, and finds the best weight proportions and uncertainties on those proportions. End of explanation """ fig = plt.figure(figsize=(6, 6)) ax = [fig.add_subplot(4, 1, 1)] ax.append(fig.add_subplot(4, 1, (2, 4))) for i, phase in enumerate(phases): ebar = plt.errorbar(pressures, weight_proportions[:, i], yerr=weight_proportion_uncertainties[:, i], fmt="none", zorder=2) ax[1].scatter(pressures, weight_proportions[:, i], label=phase, zorder=3) ax[0].set_title('Phase proportions in the Martian Mantle (Bertka and Fei, 1997)') ax[0].scatter(pressures, residuals) for i in range(2): ax[i].set_xlim(0., 40.) ax[1].set_ylim(0., 1.) ax[0].set_ylabel('Residual') ax[1].set_xlabel('Pressure (GPa)') ax[1].set_ylabel('Phase fraction (wt %)') ax[1].legend() fig.set_tight_layout(True) plt.show() """ Explanation: Finally, we plot the data. End of explanation """
murali-munna/pattern_classification
dimensionality_reduction/projection/linear_discriminant_analysis.ipynb
gpl-3.0
%load_ext watermark %watermark -v -d -u -p pandas,scikit-learn,numpy,matplotlib """ Explanation: Sebastian Raschka - Link to the containing GitHub Repository: https://github.com/rasbt/pattern_classification - Link to this IPython Notebook on GitHub: linear_discriminant_analysis.ipynb End of explanation """ feature_dict = {i:label for i,label in zip( range(4), ('sepal length in cm', 'sepal width in cm', 'petal length in cm', 'petal width in cm', ))} """ Explanation: <font size="1.5em">More information about the watermark magic command extension.</font> <hr> I would be happy to hear your comments and suggestions. Please feel free to drop me a note via twitter, email, or google+. <hr> Linear Discriminant Analysis bit by bit <br> <br> Sections Introduction Principal Component Analysis vs. Linear Discriminant Analysis What is a "good" feature subspace? Summarizing the LDA approach in 5 steps Preparing the sample data set About the Iris dataset Reading in the dataset Histograms and feature selection Standardization Normality assumptions LDA in 5 steps Step 1: Computing the d-dimensional mean vectors Step 2: Computing the Scatter Matrices Step 3: Solving the generalized eigenvalue problem for the matrix $S_{W}^{-1}S_B$ Step 4: Selecting linear discriminants for the new feature subspace Step 5: Transforming the samples onto the new subspace A comparison of PCA and LDA LDA via scikit-learn Update-scikit-learn-0.15.2 <br> <br> Introduction [back to top] Linear Discriminant Analysis (LDA) is most commonly used as dimensionality reduction technique in the pre-processing step for pattern-classification and machine learning applications. The goal is to project a dataset onto a lower-dimensional space with good class-separability in order avoid overfitting ("curse of dimensionality") and also reduce computational costs. Ronald A. Fisher formulated the Linear Discriminant in 1936 (The Use of Multiple Measurements in Taxonomic Problems), and it also has some practical uses as classifier. The original Linear discriminant was described for a 2-class problem, and it was then later generalized as "multi-class Linear Discriminant Analysis" or "Multiple Discriminant Analysis" by C. R. Rao in 1948 (The utilization of multiple measurements in problems of biological classification) The general LDA approach is very similar to a Principal Component Analysis (for more information about the PCA, see the previous article Implementing a Principal Component Analysis (PCA) in Python step by step), but in addition to finding the component axes that maximize the variance of our data (PCA), we are additionally interested in the axes that maximize the separation between multiple classes (LDA). So, in a nutshell, often the goal of an LDA is to project a feature space (a dataset n-dimensional samples) onto a smaller subspace $k$ (where $k \leq n-1$) while maintaining the class-discriminatory information. In general, dimensionality reduction does not only help reducing computational costs for a given classification task, but it can also be helpful to avoid overfitting by minimizing the error in parameter estimation ("curse of dimensionality"). <br> <br> Principal Component Analysis vs. Linear Discriminant Analysis [back to top] Both Linear Discriminant Analysis (LDA) and Principal Component Analysis (PCA) are linear transformation techniques that are commonly used for dimensionality reduction. PCA can be described as an "unsupervised" algorithm, since it "ignores" class labels and its goal is to find the directions (the so-called principal components) that maximize the variance in a dataset. In contrast to PCA, LDA is "supervised" and computes the directions ("linear discriminants") that will represent the axes that that maximize the separation between multiple classes. Although it might sound intuitive that LDA is superior to PCA for a multi-class classification task where the class labels are known, this might not always the case. For example, comparisons between classification accuracies for image recognition after using PCA or LDA show that PCA tends to outperform LDA if the number of samples per class is relatively small (PCA vs. LDA, A.M. Martinez et al., 2001). In practice, it is also not uncommon to use both LDA and PCA in combination: E.g., PCA for dimensionality reduction followed by an LDA. <br> <br> <br> <br> What is a "good" feature subspace? [back to top] Let's assume that our goal is to reduce the dimensions of a $d$-dimensional dataset by projecting it onto a $(k)$-dimensional subspace (where $k\;<\;d$). So, how do we know what size we should choose for $k$ ($k$ = the number of dimensions of the new feature subspace), and how do we know if we have a feature space that represents our data "well"? Later, we will compute eigenvectors (the components) from our data set and collect them in a so-called scatter-matrices (i.e., the in-between-class scatter matrix and within-class scatter matrix). Each of these eigenvectors is associated with an eigenvalue, which tells us about the "length" or "magnitude" of the eigenvectors. If we would observe that all eigenvalues have a similar magnitude, then this may be a good indicator that our data is already projected on a "good" feature space. And in the other scenario, if some of the eigenvalues are much much larger than others, we might be interested in keeping only those eigenvectors with the highest eigenvalues, since they contain more information about our data distribution. Vice versa, eigenvalues that are close to 0 are less informative and we might consider dropping those for constructing the new feature subspace. <br> <br> Summarizing the LDA approach in 5 steps [back to top] Listed below are the 5 general steps for performing a linear discriminant analysis; we will explore them in more detail in the following sections. Compute the $d$-dimensional mean vectors for the different classes from the dataset. Compute the scatter matrices (in-between-class and within-class scatter matrix). Compute the eigenvectors ($\pmb e_1, \; \pmb e_2, \; ..., \; \pmb e_d$) and corresponding eigenvalues ($\pmb \lambda_1, \; \pmb \lambda_2, \; ..., \; \pmb \lambda_d$) for the scatter matrices. Sort the eigenvectors by decreasing eigenvalues and choose $k$ eigenvectors with the largest eigenvalues to form a $k \times d$ dimensional matrix $\pmb W\;$ (where every column represents an eigenvector). Use this $k \times d$ eigenvector matrix to transform the samples onto the new subspace. This can be summarized by the mathematical equation: $\pmb Y = \pmb X \times \pmb W$ (where $\pmb X$ is a $n \times d$-dimensional matrix representing the $n$ samples, and $\pmb y$ are the transformed $n \times k$-dimensional samples in the new subspace). <a name="sample_data"></a> <br> <br> Preparing the sample data set [back to top] <a name="sample_data"></a> <br> <br> About the Iris dataset [back to top] For the following tutorial, we will be working with the famous "Iris" dataset that has been deposited on the UCI machine learning repository (https://archive.ics.uci.edu/ml/datasets/Iris). <font size="1"> Reference: Bache, K. & Lichman, M. (2013). UCI Machine Learning Repository. Irvine, CA: University of California, School of Information and Computer Science.</font> The iris dataset contains measurements for 150 iris flowers from three different species. The three classes in the Iris dataset: Iris-setosa (n=50) Iris-versicolor (n=50) Iris-virginica (n=50) The four features of the Iris dataset: sepal length in cm sepal width in cm petal length in cm petal width in cm End of explanation """ import pandas as pd df = pd.io.parsers.read_csv( filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None, sep=',', ) df.columns = [l for i,l in sorted(feature_dict.items())] + ['class label'] df.dropna(how="all", inplace=True) # to drop the empty line at file-end df.tail() """ Explanation: <a name="sample_data"></a> <br> <br> Reading in the dataset [back to top] End of explanation """ from sklearn.preprocessing import LabelEncoder X = df[[0,1,2,3]].values y = df['class label'].values enc = LabelEncoder() label_encoder = enc.fit(y) y = label_encoder.transform(y) + 1 label_dict = {1: 'Setosa', 2: 'Versicolor', 3:'Virginica'} """ Explanation: $\pmb X = \begin{bmatrix} x_{1_{\text{sepal length}}} & x_{1_{\text{sepal width}}} & x_{1_{\text{petal length}}} & x_{1_{\text{petal width}}}\ x_{2_{\text{sepal length}}} & x_{2_{\text{sepal width}}} & x_{2_{\text{petal length}}} & x_{2_{\text{petal width}}}\ ... \ x_{150_{\text{sepal length}}} & x_{150_{\text{sepal width}}} & x_{150_{\text{petal length}}} & x_{150_{\text{petal width}}}\ \end{bmatrix}, \;\; \pmb y = \begin{bmatrix} \omega_{\text{setosa}}\ \omega_{\text{setosa}}\ ... \ \omega_{\text{virginica}}\end{bmatrix}$ <a name="sample_data"></a> <br> <br> Since it is more convenient to work with numerical values, we will use the LabelEncode from the scikit-learn library to convert the class labels into numbers: 1, 2, and 3. End of explanation """ %matplotlib inline from matplotlib import pyplot as plt import numpy as np import math fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,6)) for ax,cnt in zip(axes.ravel(), range(4)): # set bin sizes min_b = math.floor(np.min(X[:,cnt])) max_b = math.ceil(np.max(X[:,cnt])) bins = np.linspace(min_b, max_b, 25) # plottling the histograms for lab,col in zip(range(1,4), ('blue', 'red', 'green')): ax.hist(X[y==lab, cnt], color=col, label='class %s' %label_dict[lab], bins=bins, alpha=0.5,) ylims = ax.get_ylim() # plot annotation leg = ax.legend(loc='upper right', fancybox=True, fontsize=8) leg.get_frame().set_alpha(0.5) ax.set_ylim([0, max(ylims)+2]) ax.set_xlabel(feature_dict[cnt]) ax.set_title('Iris histogram #%s' %str(cnt+1)) # hide axis ticks ax.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on") # remove axis spines ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) axes[0][0].set_ylabel('count') axes[1][0].set_ylabel('count') fig.tight_layout() plt.show() """ Explanation: $\pmb y = \begin{bmatrix}{\text{setosa}}\ {\text{setosa}}\ ... \ {\text{virginica}}\end{bmatrix} \quad \Rightarrow \begin{bmatrix} {\text{1}}\ {\text{1}}\ ... \ {\text{3}}\end{bmatrix}$ <a name="sample_data"></a> <br> <br> Histograms and feature selection [back to top] Just to get a rough idea how the samples of our three classes $\omega_1$, $\omega_2$ and $\omega_3$ are distributed, let us visualize the distributions of the four different features in 1-dimensional histograms. End of explanation """ from sklearn import preprocessing preprocessing.scale(X, axis=0, with_mean=True, with_std=True, copy=False) print() """ Explanation: From just looking at these simple graphical representations of the features, we can already tell that the petal lengths and widths are likely better suited as potential features two separate between the three flower classes. In practice, instead of reducing the dimensionality via a projection (here: LDA), a good alternative would be a feature selection technique. For low-dimensional datasets like Iris, a glance at those histograms would already be very informative. Another simple, but very useful technique would be to use feature selection algorithms, which I have described in more detail in another article: Feature Selection Algorithms in Python <a name="sample_data"></a> <br> <br> Standardization [back to top] Normalization is one important part of every data pre-processing step and typically a requirement for best performances of many machine learning algorithms. The two most popular approaches for data normalization are the so-called "standardization" and "min-max scaling". Standardization (or Z-score normalization): Rescaling of the features so that they'll have the properties of a standard normal distribution with &mu;=0 and &sigma;=1 (i.e., unit variance centered around the mean). Min-max scaling: Rescaling of the features to unit range, typically a range between 0 and 1. Quite often, min-max scaling is also just called "normalization", which can be quite confusing depending on the context where the term is being used. Via Min-max scaling, Both are very important procedures, so that I have also a separate article about it with more details: About Feature Scaling and Normalization. In our case, although the features are already on the same scale (measured in centimeters), we still want to scale the features to unit variance (&sigma;=1, &mu;=0). End of explanation """ np.set_printoptions(precision=4) mean_vectors = [] for cl in range(1,4): mean_vectors.append(np.mean(X[y==cl], axis=0)) print('Mean Vector class %s: %s\n' %(cl, mean_vectors[cl-1])) """ Explanation: <a name="sample_data"></a> <br> <br> Normality assumptions [back to top] It should be mentioned that LDA assumes normal distributed data, features that are statistically independent, and identical covariance matrices for every class. However, this only applies for LDA as classifier and LDA for dimensionality reduction can also work reasonably well if those assumptions are violated. And even for classification tasks LDA seems can be quite robust to the distribution of the data: "linear discriminant analysis frequently achieves good performances in the tasks of face and object recognition, even though the assumptions of common covariance matrix among groups and normality are often violated (Duda, et al., 2001)" (Tao Li, et al., 2006). <br> <font size="1">References: Tao Li, Shenghuo Zhu, and Mitsunori Ogihara. “Using Discriminant Analysis for Multi-Class Classification: An Experimental Investigation.” Knowledge and Information Systems 10, no. 4 (2006): 453–72.) Duda, Richard O, Peter E Hart, and David G Stork. 2001. Pattern Classification. New York: Wiley.</font> <a name="sample_data"></a> <br> <br> LDA in 5 steps [back to top] After we went through several preparation steps, our data is finally ready for the actual LDA. In practice, LDA for dimensionality reduction would be just another preprocessing step for a typical machine learning or pattern classification task. <a name="sample_data"></a> <br> <br> Step 1: Computing the d-dimensional mean vectors [back to top] In this first step, we will start off with a simple computation of the mean vectors $\pmb m_i$, $(i = 1,2,3)$ of the 3 different flower classes: $\pmb m_i = \begin{bmatrix} \mu_{\omega_i (\text{sepal length)}}\ \mu_{\omega_i (\text{sepal width})}\ \mu_{\omega_i (\text{petal length)}}\ \mu_{\omega_i (\text{petal width})}\ \end{bmatrix} \; , \quad \text{with} \quad i = 1,2,3$ End of explanation """ S_W = np.zeros((4,4)) for cl,mv in zip(range(1,4), mean_vectors): class_sc_mat = np.zeros((4,4)) # scatter matrix for every class for row in X[y == cl]: row, mv = row.reshape(4,1), mv.reshape(4,1) # make column vectors class_sc_mat += (row-mv).dot((row-mv).T) S_W += class_sc_mat # sum class scatter matrices print('within-class Scatter Matrix:\n', S_W) """ Explanation: <a name="sample_data"></a> <br> <br> <a name="sc_matrix"></a> Step 2: Computing the Scatter Matrices [back to top] Now, we will compute the two 4x4-dimensional matrices: The within-class and the between-class scatter matrix. <br> <br> 2.1 Within-class scatter matrix $S_W$ [back to top] The within-class scatter matrix $S_W$ is computed by the following equation: $S_W = \sum\limits_{i=1}^{c} S_i$ where $S_i = \sum\limits_{\pmb x \in D_i}^n (\pmb x - \pmb m_i)\;(\pmb x - \pmb m_i)^T$ (scatter matrix for every class) and $\pmb m_i$ is the mean vector $\pmb m_i = \frac{1}{n_i} \sum\limits_{\pmb x \in D_i}^n \; \pmb x_k$ End of explanation """ overall_mean = np.mean(X, axis=0) S_B = np.zeros((4,4)) for i,mean_vec in enumerate(mean_vectors): n = X[y==i+1,:].shape[0] mean_vec = mean_vec.reshape(4,1) # make column vector overall_mean = overall_mean.reshape(4,1) # make column vector S_B += n * (mean_vec - overall_mean).dot((mean_vec - overall_mean).T) print('between-class Scatter Matrix:\n', S_B) """ Explanation: <br> 2.1 b Alternatively, we could also compute the class-covariance matrices by adding the scaling factor $\frac{1}{N-1}$ to the within-class scatter matrix, so that our equation becomes $\Sigma_i = \frac{1}{N_{i}-1} \sum\limits_{\pmb x \in D_i}^n (\pmb x - \pmb m_i)\;(\pmb x - \pmb m_i)^T$. and $S_W = \sum\limits_{i=1}^{c} (N_{i}-1) \Sigma_i$ where $N_{i}$ is the sample size of the respective class (here: 50), and in this particular case, we can drop the term ($N_{i}-1)$ since all classes have the same sample size. However, the resulting eigenspaces will be identical (identical eigenvectors, only the eigenvalues are scaled differently by a constant factor). <br> <br> 2.2 Between-class scatter matrix $S_B$ [back to top] The between-class scatter matrix $S_B$ is computed by the following equation: $S_B = \sum\limits_{i=1}^{c} N_{i} (\pmb m_i - \pmb m) (\pmb m_i - \pmb m)^T$ where $\pmb m$ is the overall mean, and $\pmb m_{i}$ and $N_{i}$ are the sample mean and sizes of the respective classes. End of explanation """ eig_vals, eig_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B)) for i in range(len(eig_vals)): eigvec_sc = eig_vecs[:,i].reshape(4,1) print('\nEigenvector {}: \n{}'.format(i+1, eigvec_sc.real)) print('Eigenvalue {:}: {:.2e}'.format(i+1, eig_vals[i].real)) """ Explanation: <br> <br> Step 3: Solving the generalized eigenvalue problem for the matrix $S_{W}^{-1}S_B$ [back to top] Next, we will solve the generalized eigenvalue problem for the matrix $S_{W}^{-1}S_B$ to obtain the linear discriminants. End of explanation """ for i in range(len(eig_vals)): eigv = eig_vecs[:,i].reshape(4,1) np.testing.assert_array_almost_equal(np.linalg.inv(S_W).dot(S_B).dot(eigv), eig_vals[i] * eigv, decimal=6, err_msg='', verbose=True) print('ok') """ Explanation: <br> <br> After this decomposition of our square matrix into eigenvectors and eigenvalues, let us briefly recapitulate how we can interpret those results. As we remember from our first linear algebra class in high school or college, both eigenvectors and eigenvalues are providing us with information about the distortion of a linear transformation: The eigenvectors are basically the direction of this distortion, and the eigenvalues are the scaling factor for the eigenvectors that describing the magnitude of the distortion. If we are performing the LDA for dimensionality reduction, the eigenvectors are important since they will form the new axes of our new feature subspace; the associated eigenvalues are of particular interest since they will tell us how "informative" the new "axes" are. Let us briefly double-check our calculation and talk more about the eigenvalues in the next section. <br> <br> Checking the eigenvector-eigenvalue calculation [back to top] A quick check that the eigenvector-eigenvalue calculation is correct and satisfy the equation: $\pmb A\pmb{v} = \lambda\pmb{v}$ <br> where $\pmb A = S_{W}^{-1}S_B\ \pmb{v} = \; \text{Eigenvector}\ \lambda = \; \text{Eigenvalue}$ End of explanation """ # Make a list of (eigenvalue, eigenvector) tuples eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))] # Sort the (eigenvalue, eigenvector) tuples from high to low eig_pairs = sorted(eig_pairs, key=lambda k: k[0], reverse=True) # Visually confirm that the list is correctly sorted by decreasing eigenvalues print('Eigenvalues in decreasing order:\n') for i in eig_pairs: print(i[0]) """ Explanation: <br> <br> Step 4: Selecting linear discriminants for the new feature subspace [back to top] <br> <br> 4.1. Sorting the eigenvectors by decreasing eigenvalues [back to top] Remember from the introduction that we are not only interested in merely projecting the data into a subspace that improves the class separability, but also reduces the dimensionality of our feature space, (where the eigenvectors will form the axes of this new feature subspace). However, the eigenvectors only define the directions of the new axis, since they have all the same unit length 1. So, in order to decide which eigenvector(s) we want to drop for our lower-dimensional subspace, we have to take a look at the corresponding eigenvalues of the eigenvectors. Roughly speaking, the eigenvectors with the lowest eigenvalues bear the least information about the distribution of the data, and those are the ones we want to drop. The common approach is to rank the eigenvectors from highest to lowest corresponding eigenvalue and choose the top $k$ eigenvectors. End of explanation """ print('Variance explained:\n') eigv_sum = sum(eig_vals) for i,j in enumerate(eig_pairs): print('eigenvalue {0:}: {1:.2%}'.format(i+1, (j[0]/eigv_sum).real)) """ Explanation: <br> <br> If we take a look at the eigenvalues, we can already see that 2 eigenvalues are close to 0 and conclude that the eigenpairs are less informative than the other two. Let's express the "explained variance" as percentage: End of explanation """ W = np.hstack((eig_pairs[0][1].reshape(4,1), eig_pairs[1][1].reshape(4,1))) print('Matrix W:\n', W.real) """ Explanation: <br> <br> The first eigenpair is by far the most informative one, and we won't loose much information if we would form a 1D-feature spaced based on this eigenpair. <br> <br> 4.2. Choosing k eigenvectors with the largest eigenvalues [back to top] After sorting the eigenpairs by decreasing eigenvalues, it is now time to construct our $k \times d$-dimensional eigenvector matrix $\pmb W$ (here $4 \times 2$: based on the 2 most informative eigenpairs) and thereby reducing the initial 4-dimensional feature space into a 2-dimensional feature subspace. End of explanation """ X_lda = X.dot(W) assert X_lda.shape == (150,2), "The matrix is not 2x150 dimensional." from matplotlib import pyplot as plt def plot_step_lda(): ax = plt.subplot(111) for label,marker,color in zip( range(1,4),('^', 's', 'o'),('blue', 'red', 'green')): plt.scatter(x=X_lda[:,0].real[y == label], y=X_lda[:,1].real[y == label], marker=marker, color=color, alpha=0.5, label=label_dict[label] ) plt.xlabel('LD1') plt.ylabel('LD2') leg = plt.legend(loc='upper right', fancybox=True) leg.get_frame().set_alpha(0.5) plt.title('LDA: Iris projection onto the first 2 linear discriminants') # hide axis ticks plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on") # remove axis spines ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) plt.grid() plt.tight_layout plt.show() plot_step_lda() """ Explanation: <br> <br> Step 5: Transforming the samples onto the new subspace [back to top] In the last step, we use the $4 \times 2$-dimensional matrix $\pmb W$ that we just computed to transform our samples onto the new subspace via the equation $\pmb Y = \pmb X \times \pmb W $. (where $\pmb X$ is a $n \times d$-dimensional matrix representing the $n$ samples, and $\pmb Y$ are the transformed $n \times k$-dimensional samples in the new subspace). End of explanation """ from sklearn.decomposition import PCA as sklearnPCA sklearn_pca = sklearnPCA(n_components=2) X_pca = sklearn_pca.fit_transform(X) def plot_pca(): ax = plt.subplot(111) for label,marker,color in zip( range(1,4),('^', 's', 'o'),('blue', 'red', 'green')): plt.scatter(x=X_pca[:,0][y == label], y=X_pca[:,1][y == label], marker=marker, color=color, alpha=0.5, label=label_dict[label] ) plt.xlabel('PC1') plt.ylabel('PC2') leg = plt.legend(loc='upper right', fancybox=True) leg.get_frame().set_alpha(0.5) plt.title('PCA: Iris projection onto the first 2 principal components') # hide axis ticks plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on") # remove axis spines ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) plt.tight_layout plt.grid() plt.show() plot_pca() plot_step_lda() """ Explanation: The scatter plot above represents our new feature subspace that we constructed via LDA. We can see that the first linear discriminant "LD1" separates the classes quite nicely. However, the second discriminant, "LD2", does not add much valuable information, which we've already concluded when we looked at the ranked eigenvalues is step 4. <br> <br> A comparison of PCA and LDA [back to top] In order to compare the feature subspace that we obtained via the Linear Discriminant Analysis, we will use the PCA class from the scikit-learn machine-learning library. The documentation can be found here: http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html. For our convenience, we can directly specify to how many components we want to retain in our input dataset via the n_components parameter. n_components : int, None or string Number of components to keep. if n_components is not set all components are kept: n_components == min(n_samples, n_features) if n_components == ‘mle’, Minka’s MLE is used to guess the dimension if 0 &lt; n_components &lt; 1, select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components <br> <br> But before we skip to the results of the respective linear transformations, let us quickly recapitulate the purposes of PCA and LDA: PCA finds the axes with maximum variance for the whole data set where LDA tries to find the axes for best class seperability. In practice, often a LDA is done followed by a PCA for dimensionality reduction. <br> <br> <br> <br> End of explanation """ from sklearn.lda import LDA # LDA sklearn_lda = LDA(n_components=2) X_lda_sklearn = sklearn_lda.fit_transform(X, y) def plot_scikit_lda(X, title, mirror=1): ax = plt.subplot(111) for label,marker,color in zip( range(1,4),('^', 's', 'o'),('blue', 'red', 'green')): plt.scatter(x=X[:,0][y == label]*mirror, y=X[:,1][y == label], marker=marker, color=color, alpha=0.5, label=label_dict[label] ) plt.xlabel('LD1') plt.ylabel('LD2') leg = plt.legend(loc='upper right', fancybox=True) leg.get_frame().set_alpha(0.5) plt.title(title) # hide axis ticks plt.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on") # remove axis spines ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) plt.grid() plt.tight_layout plt.show() plot_step_lda() plot_scikit_lda(X_lda_sklearn, title='Default LDA via scikit-learn', mirror=(-1)) """ Explanation: <br> <br> The two plots above nicely confirm what we have discussed before: Where the PCA accounts for the most variance in the whole dataset, the LDA gives us the axes that account for the most variance between the individual classes. <br> <br> LDA via scikit-learn [back to top] Now, after we have seen how an Linear Discriminant Analysis works using a step-by-step approach, there is also a more convenient way to achive the same via the LDA class implemented in the scikit-learn machine learning library. End of explanation """
giacomov/3ML
docs/notebooks/The_3ML_workflow.ipynb
bsd-3-clause
from threeML import * import matplotlib.pyplot as plt %matplotlib notebook plt.style.use('mike') import warnings warnings.filterwarnings('ignore') """ Explanation: The 3ML workflow Generally, an analysis in 3ML is performed in 3 steps: Load the data: one or more datasets are loaded and then listed in a DataList object Define the model: a model for the data is defined by including one or more PointSource, ExtendedSource or ParticleSource instances Perform a likelihood or a Bayesian analysis: the data and the model are used together to perform either a Maximum Likelihood analysis, or a Bayesian analysis Loading data 3ML is built around the concept of plugins. A plugin is used to load a particular type of data, or the data from a particular instrument. There is a plugin of optical data, one for X-ray data, one for Fermi/LAT data and so on. Plugins instances can be added and removed at the loading stage without changing any other stage of the analysis (but of course, you need to rerun all stages to update the results). First, let's import 3ML: End of explanation """ # Get some example data from threeML.io.package_data import get_path_of_data_file data_path = get_path_of_data_file("datasets/xy_powerlaw.txt") # Create an instance of the XYLike plugin, which allows to analyze simple x,y points # with error bars xyl = XYLike.from_text_file("xyl", data_path) # Let's plot it just to see what we have loaded fig = xyl.plot(x_scale='log', y_scale='log') """ Explanation: Let's start by loading one dataset, which in the 3ML workflow means creating an instance of the appropriate plugin: End of explanation """ data = DataList(xyl) """ Explanation: Now we need to create a DataList object, which in this case contains only one instance: End of explanation """ # Create the second instance, this time of a different type pha = get_path_of_data_file("datasets/ogip_powerlaw.pha") bak = get_path_of_data_file("datasets/ogip_powerlaw.bak") rsp = get_path_of_data_file("datasets/ogip_powerlaw.rsp") ogip = OGIPLike("ogip", pha, bak, rsp) # Now use both plugins data = DataList(xyl, ogip) """ Explanation: The DataList object can receive one or more plugin instances on initialization. So for example, to use two datasets we can simply do: End of explanation """ # This is equivalent to write data = DataList(xyl, ogip) my_plugins = [xyl, ogip] data = DataList(*my_plugins) """ Explanation: The DataList object can accept any number of plugins in input. You can also create a list of plugins, and then create a DataList using the "expansion" feature of the python language ('*'), like this: End of explanation """ # A point source with a power law spectrum source1_sp = Powerlaw() source1 = PointSource("source1", ra=23.5, dec=-22.7, spectral_shape=source1_sp) # Another source with a log-parabolic spectrum plus a power law source2_sp = Log_parabola() + Powerlaw() source2 = PointSource("source2", ra=30.5, dec=-27.1, spectral_shape=source2_sp) # A third source defined in terms of its Galactic latitude and longitude source3_sp = Cutoff_powerlaw() source3 = PointSource("source3", l=216.1, b=-74.56, spectral_shape=source3_sp) """ Explanation: This is useful if you need to create the list of plugins at runtime, for example looping over many files. Define the model After you have loaded your data, you need to define a model for them. A model is a collection of one or more sources. A source represents an astrophysical reality, like a star, a galaxy, a molecular cloud... There are 3 kinds of sources: PointSource, ExtendedSource and ParticleSource. The latter is used only in special situations. The models are defined using the package astromodels. Here we will only go through the basics. You can find a lot more information here: astromodels.readthedocs.org Point sources A point source is characterized by a name, a position, and a spectrum. These are some examples: End of explanation """ # An extended source with a Gaussian shape centered on R.A., Dec = (30.5, -27.1) # and a sigma of 3.0 degrees ext1_spatial = Gaussian_on_sphere(lon0=30.5, lat0=-27.1, sigma=3.0) ext1_spectral = Powerlaw() ext1 = ExtendedSource("ext1", ext1_spatial, ext1_spectral) # An extended source with a 3D function # (i.e., the function defines both the spatial and the spectral shape) ext2_spatial = Continuous_injection_diffusion() ext2 = ExtendedSource("ext2", ext2_spatial) """ Explanation: Extended sources An extended source is characterized by its spatial shape and its spectral shape: End of explanation """ model = Model(source1, source2, source3, ext1, ext2) # We can see a summary of the model like this: model.display(complete=True) """ Explanation: NOTE: not all plugins support extended sources. For example, the XYLike plugin we used above do not, as it is meant for data without spatial resolution. Create the likelihood model Now that we have defined our sources, we can create a model simply as: End of explanation """ # Fix a parameter model.source1.spectrum.main.Powerlaw.K.fix = True # or model.source1.spectrum.main.Powerlaw.K.free = False # Free it again model.source1.spectrum.main.Powerlaw.K.free = True # or model.source1.spectrum.main.Powerlaw.K.fix = False # Change the value model.source1.spectrum.main.Powerlaw.K = 2.3 # or using physical units (need to be compatible with what shown # in the table above) model.source1.spectrum.main.Powerlaw.K = 2.3 * 1 / (u.cm**2 * u.s * u.TeV) # Change the boundaries for the parameter model.source1.spectrum.main.Powerlaw.K.bounds = (1e-10, 1.0) # you can use units here as well, like: model.source1.spectrum.main.Powerlaw.K.bounds = (1e-5 * 1 / (u.cm**2 * u.s * u.TeV), 10.0 * 1 / (u.cm**2 * u.s * u.TeV)) # Link two parameters so that they are forced to have the same value model.link(model.source2.spectrum.main.composite.K_1, model.source1.spectrum.main.Powerlaw.K) # Link two parameters with a law. The parameters of the law become free # parameters in the fit. In this case we impose a linear relationship # between the index of the log-parabolic spectrum and the index of the # powerlaw in source2: index_2 = a * alpha_1 + b. law = Line() model.link(model.source2.spectrum.main.composite.index_2, model.source2.spectrum.main.composite.alpha_1, law) # If you want to force them to be in a specific relationship, # say index_2 = alpha_1 + 1, just fix a and b to the corresponding values, # after the linking, like: # model.source2.spectrum.main.composite.index_2.Line.a = 1.0 # model.source2.spectrum.main.composite.index_2.Line.a.fix = True # model.source2.spectrum.main.composite.index_2.Line.b = 0.0 # model.source2.spectrum.main.composite.index_2.Line.b.fix = True # Now display() will show the links model.display(complete=True) """ Explanation: You can easily interact with the model. For example: End of explanation """ new_model = Model(source1) source1_sp.K.bounds = (0.01, 100) """ Explanation: Now, for the following steps, let's keep it simple and let's use a single point source: End of explanation """ new_model.save("new_model.yml", overwrite=True) new_model_reloaded = load_model("new_model.yml") """ Explanation: A model can be saved to disk, and reloaded from disk, as: End of explanation """ data = DataList(ogip) jl = JointLikelihood(new_model, data) best_fit_parameters, likelihood_values = jl.fit() """ Explanation: The output is in YAML format, a human-readable text-based format. Perform the analysis Maximum likelihood analysis Now that we have the data and the model, we can perform an analysis very easily: End of explanation """ jl.results.display() """ Explanation: The output of the fit() method of the JointLikelihood object consists of two pandas DataFrame objects, which can be queried, saved to disk, reloaded and so on. Refer to the pandas manual for details. After the fit the JointLikelihood instance will have a .results attribute which contains the results of the fit. End of explanation """ jl.results.write_to("my_results.fits", overwrite=True) """ Explanation: This object can be saved to disk in a FITS file: End of explanation """ results_reloaded = load_analysis_results("my_results.fits") results_reloaded.display() """ Explanation: The produced FITS file contains the complete definition of the model and of the results, so it can be reloaded in a separate session as: End of explanation """ fluxes = jl.results.get_flux(100 * u.keV, 1 * u.MeV) # Same results would be obtained with # fluxes = results_reloaded.get_point_source_flux(100 * u.keV, 1 * u.MeV) """ Explanation: The flux of the source can be computed from the 'results' object (even in another session by reloading the FITS file), as: End of explanation """ fig = plot_spectra(jl.results, ene_min=0.1, ene_max=1e6, num_ene=500, flux_unit='erg / (cm2 s)') """ Explanation: We can also plot the spectrum with its error region, as: End of explanation """ # It can be set using the currently defined boundaries new_model.source1.spectrum.main.Powerlaw.index.set_uninformative_prior(Uniform_prior) # or uniform prior can be defined directly, like: new_model.source1.spectrum.main.Powerlaw.index.prior = Uniform_prior(lower_bound=-3, upper_bound=0) # The same for the Log_uniform prior new_model.source1.spectrum.main.Powerlaw.K.prior = Log_uniform_prior(lower_bound=1e-3, upper_bound=100) # or new_model.source1.spectrum.main.Powerlaw.K.set_uninformative_prior(Log_uniform_prior) new_model.display(complete=True) """ Explanation: Bayesian analysis In a very similar way, we can also perform a Bayesian analysis. As a first step, we need to define the priors for all parameters: End of explanation """ bs = BayesianAnalysis(new_model, data) bs.set_sampler('ultranest') bs.sampler.setup() # This uses the emcee sampler samples = bs.sample(quiet=True) """ Explanation: Then, we can perform our Bayesian analysis like: End of explanation """ bs.results.display() fluxes_bs = bs.results.get_flux(100 * u.keV, 1 * u.MeV) fig = plot_spectra(bs.results, ene_min=0.1, ene_max=1e6, num_ene=500, flux_unit='erg / (cm2 s)') """ Explanation: The BayesianAnalysis object will now have a "results" member which will work exactly the same as explained for the Maximum Likelihood analysis (see above): End of explanation """ bs.results.corner_plot(); """ Explanation: We can also produce easily a "corner plot", like: End of explanation """
steinam/teacher
jup_notebooks/.ipynb_checkpoints/Versicherung_11FI3_On_Paper-checkpoint.ipynb
mit
%load_ext sql %sql mysql://steinam:steinam@localhost/versicherung_complete """ Explanation: Versicherung on Paper End of explanation """ %%sql -- meine Lösung select distinct(Land) from Fahrzeughersteller; %%sql -- deine Lösung select fahrzeughersteller.Land from fahrzeughersteller group by fahrzeughersteller.Land ; """ Explanation: Gesucht wird eine wiederholungsfreie Liste der Herstellerländer 3 P End of explanation """ %%sql -- meine Lösung select fahrzeugtyp.Bezeichnung, count(fahrzeug.iD) as Anzahl from fahrzeugtyp left join fahrzeug on fahrzeugtyp.id = fahrzeug.fahrzeugtyp_id group by fahrzeugtyp.bezeichnung having count(Anzahl) > 2 %%sql select *, (select count(*) from fahrzeug where fahrzeug.fahrzeugtyp_id = fahrzeugtyp.id) as Fahrzeuge from fahrzeugtyp having Fahrzeuge > 2 order by fahrzeugtyp.bezeichnung; """ Explanation: Listen Sie alle Fahrzeugtypen und die Anzahl Fahrzeuge dieses Typs, aber nur, wenn mehr als 2 Fahrzeuge des Typs vorhanden sind. Sortieren Sie die Ausgabe nach Fahrzeugtypen. 4 P End of explanation """ %%sql -- meine Lösung -- select ID from Abteilung where Abteilung.Ort = 'Dortmund' or abteilung.Ort = 'Bochum' select Name, vorname, Bezeichnung, Abteilung.ID, Mitarbeiter.Abteilung_ID, Abteilung.Ort from Mitarbeiter inner join Abteilung on Mitarbeiter.Abteilung_ID = Abteilung.ID where Abteilung.Ort in('Dortmund', 'Bochum') order by Name %%sql -- deine Lösung select mitarbeiter.Name, mitarbeiter.Vorname, (select abteilung.bezeichnung from abteilung where abteilung.id = mitarbeiter.abteilung_id) as Abteilung, (select abteilung.ort from abteilung where abteilung.id = mitarbeiter.abteilung_id) as Standort from mitarbeiter having Standort = "Dortmund" or Standort = "Bochum"; """ Explanation: Ermittle die Namen und Vornamen der Mitarbeiter incl. Abteilungsname, deren Abteilung ihren Sitz in Dortmund oder Bochum hat. End of explanation """ %%sql -- meine Lösung select fahrzeughersteller.id, year(datum) as Jahr, min(zuordnung_sf_fz.schadenshoehe), max(zuordnung_sf_fz.Schadenshoehe), (max(zuordnung_sf_fz.schadenshoehe) - min(zuordnung_sf_fz.schadenshoehe)) as Differenz from fahrzeughersteller left join fahrzeugtyp on fahrzeughersteller.id = fahrzeugtyp.hersteller_ID inner join fahrzeug on fahrzeugtyp.id = fahrzeug.fahrzeugtyp_id inner join zuordnung_sf_fz on fahrzeug.id = zuordnung_sf_fz.fahrzeug_id inner join schadensfall on schadensfall.id = zuordnung_sf_fz.schadensfall_id group by fahrzeughersteller.id, year(datum) %%sql -- redigierte Version von Wortmann geht select fahrzeughersteller.Name, (select min(zuordnung_sf_fz.schadenshoehe) from zuordnung_sf_fz where zuordnung_sf_fz.fahrzeug_id in( select fahrzeug.id from fahrzeug where fahrzeug.fahrzeugtyp_id in( select fahrzeugtyp.id from fahrzeugtyp where fahrzeugtyp.hersteller_id = fahrzeughersteller.id ) ) ) as Kleinste, (select max(zuordnung_sf_fz.schadenshoehe) from zuordnung_sf_fz where zuordnung_sf_fz.fahrzeug_id in( select fahrzeug.id from fahrzeug where fahrzeug.fahrzeugtyp_id in( select fahrzeugtyp.id from fahrzeugtyp where fahrzeugtyp.hersteller_id = fahrzeughersteller.id ) ) ) as `Groesste` from fahrzeughersteller; """ Explanation: Gesucht wird für jeden Fahrzeughersteller (Angabe der ID reicht) und jedes Jahr die kleinste und größte Schadenshöhe. Geben Sie falls möglich auch die Differenz zwischen den beiden Werten mit in der jeweiligen Ergebnismenge aus. Ansonsten erzeugen Sie für diese Aufgabe ein eigenes sql-Statement. 5 P End of explanation """ %%sql select Mitarbeiter.Name, dienstwagen.Kennzeichen from Mitarbeiter inner join dienstwagen on mitarbeiter.id = dienstwagen.Mitarbeiter_id inner join fahrzeugtyp on dienstwagen.fahrzeugtyp_Id = fahrzeugtyp.id inner join fahrzeughersteller on fahrzeugtyp.hersteller_id = fahrzeughersteller.id where Fahrzeughersteller.NAme = 'Opel' %%sql select * from mitarbeiter where mitarbeiter.id in( select dienstwagen.mitarbeiter_id from dienstwagen where dienstwagen.mitarbeiter_id = mitarbeiter.id and dienstwagen.fahrzeugtyp_id in( select fahrzeugtyp.id from fahrzeugtyp where fahrzeugtyp.hersteller_id in( select fahrzeughersteller.id from fahrzeughersteller where fahrzeughersteller.name = "Opel" ) ) ) """ Explanation: Zeige alle Mitarbeiter und deren Autokennzeichen, die als Dienstwagen einen Opel fahren. 4 P End of explanation """ %%sql select fahrzeug.kennzeichen, sum(schadenshoehe) from fahrzeug inner join zuordnung_sf_fz on fahrzeug.id = zuordnung_sf_fz.fahrzeug_id group by fahrzeug.kennzeichen having sum(schadenshoehe) > (select avg(schadenshoehe) from zuordnung_sf_fz) %%sql -- deine Lösung Wortmann /* select * from fahrzeug having fahrzeug.id in( select zuordnung_sf_zf.fahrzeugtyp_id from zuordnung_sf_zf where zuordnung_sf_zf.schadenhoehe > ((select sum(zuordnung_sf_zf.schadenhoehe) from zuordnung_sf_zf)) / (select count(*) from zuordnung_sf_zf)) */ select * from fahrzeug having fahrzeug.id in( select zuordnung_sf_fz.fahrzeug_id from zuordnung_sf_fz where zuordnung_sf_fz.schadenshoehe > ((select sum(zuordnung_sf_fz.schadenshoehe) from zuordnung_sf_fz)) / (select count(*) from zuordnung_sf_fz)) """ Explanation: Welche Fahrzeuge haben Schäden verursacht, deren Schadenssumme höher als die durchschnittliche Schadenshöhe sind. 5 P End of explanation """ %%sql select Mitarbeiter.Name, Mitarbeiter.Geburtsdatum from Mitarbeiter where Geburtsdatum < (select avg(Geburtsdatum) from Mitarbeiter ma) order by Mitarbeiter.Name %%sql -- geht auch select ma.Name, ma.Geburtsdatum from Mitarbeiter ma where (now() - ma.Geburtsdatum) < (now() - (select avg(geburtsdatum) from mitarbeiter)) order by ma.Name; %%sql -- deine Lösung Wortmann select * from mitarbeiter having mitarbeiter.geburtsdatum < (select sum(mitarbeiter.geburtsdatum) from mitarbeiter) / (select count(*) from mitarbeiter) """ Explanation: Welche Mitarbeiter sind älter als das Durchschnittsalter der Mitarbeiter. 4 P End of explanation """
ComputationalModeling/spring-2017-danielak
past-semesters/fall_2016/day-by-day/day17-analyzing-tweets-with-string-processing/In-Class-Strings.ipynb
agpl-3.0
%matplotlib inline import matplotlib.pyplot as plt from string import punctuation """ Explanation: Day 17 In-class assignment: Data analysis and Modeling in Social Sciences Part 3 The first part of this notebook is a copy of a blog post tutorial written by Dr. Neal Caren (University of North Carolina, Chapel Hill). The format was modified to fit into a Jupyter Notebook, ported from python2 to python3, and adjusted to meet the goals of this class. Here is a link to the original tutorial: http://nealcaren.web.unc.edu/an-introduction-to-text-analysis-with-python-part-3/ Student Names // Put the names of everybody in your group here! Learning Goals Natural Language Processing can be tricky to model comparied to known physical processes with mathematical rules. A large part of modeling is trying to understand a model's limitations and determining what can be learned from a model despite its limitations: Apply what we have learned from the Pre-class notebooks to build a Twitter "bag of words" model on real Twitter data. Introduce you to a method for downloading data from the Internet. Gain practice doing string manipulation. Learn how to make Pie Charts in Python. This assignment explains how to expand the code written in your pre-class assignemnt so that you can use it to explore the positive and negative sentiment of any set of texts. Specifically, we’ll look at looping over more than one tweet, incorporating a more complete dictionary, and exporting the results. Earlier, we used a small list of words to measure positive sentiment. While the study in Science used the commercial LIWC dictionary, an alternate sentiment dictionary is produced by Theresa Wilson, Janyce Wiebe, and Paul Hoffmann at the University of Pittsburgh and is freely available. In both cases, the sentiment dictionaries are used in a fairly straightforward way: the more positive words in the text, the higher the text scores on the positive sentiment scale. While this has some drawbacks, the method is quite popular: the LIWC database has over 1,000 citations in Google Scholar, and the Wilson et al. database has more than 600. Do the following on your own: First, load some libraries we will be using in this notebook. End of explanation """ import urllib.request """ Explanation: Downloading Since the Wilson et al. list combines negative and positive polarity words in one list, and includes both words and word stems, Dr. Caren cleaned it up a bit for us. You can download the positive list and the negative list using your browser, but you don’t have to. Python can do that. First, you need to import one of the modules that Python uses to communicate with the Internet: End of explanation """ url='http://www.unc.edu/~ncaren/haphazard/negative.txt' """ Explanation: Like many commands, Python won’t return anything unless something went wrong. In this case, the In [*] should change to a number like In [2]. Next, store the web address that you want to access in a string. You don’t have to do this, but it’s the type of thing that makes your code easier to read and allows you to scale up quickly when you want to download thousands of urls. End of explanation """ file_name='negative.txt' """ Explanation: You can also create a string with the name you want the file to have on you hard drive: End of explanation """ urllib.request.urlretrieve(url, file_name) """ Explanation: To download and save the file: End of explanation """ urllib.request.urlretrieve('http://www.unc.edu/~ncaren/haphazard/negative.txt','negative.txt') """ Explanation: This will download the file into your current directory. If you want it to go somewhere else, you can put the full path in the file_name string. You didn’t have to enter the url and the file name in the prior lines. Something like the following would have worked exactly the same: End of explanation """ # get negative and positive words files=['negative.txt','positive.txt'] path='http://www.unc.edu/~ncaren/haphazard/' for file_name in files: urllib.request.urlretrieve(path+file_name,file_name) # get politician tweets files=['BarackObama_tweets.txt','HillaryClinton_tweets.txt', 'realDonaldTrump_tweets.txt','mike_pence_tweets.txt', 'timkaine_tweets.txt'] path='https://raw.githubusercontent.com/bwoshea/CMSE201_datasets/master/pres_tweets/' for file_name in files: urllib.request.urlretrieve(path+file_name,file_name) """ Explanation: Note that the location and filename are both surrounded by quotation marks because you want Python to use this information literally; they aren’t referring to a string object, like in our previous code. This line of code is actually quite readable, and in most circumstances this would be the most efficient thing to do. But there are actually lots of files that we want to get: the negative list, the positive list, and several lists of tweets. And we can download the datasets using a couple of simple loops: End of explanation """ tweets = open("CHOOSE_YOUR_FILE_NAME_tweets.txt").read() """ Explanation: The first line creates a new list with two items - the names of the two files to be downloaded. The second line creates a string object that stores the url path that they all share. The third line starts a loop over each of the items in the files list using file_name to reference each item in turn. The fourth line is indented, because it happens once for each item in the list as a result of the loop, and downloads the file. This is the same as the original download line, except the URL is now the combination of two strings, path and file_name. As noted previously, Python can combine strings with a plus sign, so the result from the first pass through the loop will be http://www.unc.edu/~ncaren/haphazard/negative.txt, which is where the file can be found. Note that this takes advantage of the fact that we don’t mind reusing the original file name. If we wanted to change it, or if there were different paths to each of the files, things would get slightly trickier. The second set of files, url path, and loop will download collections of tweets from various politicians involved in the current Presidential election: the sitting president (Barack Obama), the two candidates (Hillary Clinton and Donald Trump) and their vice-presidential running mates (Tim Kaine and Mike Pence). Everybody should pick one of these people to analyze - coordinate with your group members! More fun with lists Let’s take a look at the list of Tweets that we just downloaded. First, pick one of the politicians to analyze and open the appropriate file (you're going to have to change some stuff to do so): End of explanation """ tweets_list = tweets.split('\n') """ Explanation: As you might have guessed, this line is actually doing double duty. It opens the file and reads it into memory before it is stored in tweets. Since the file has one tweet on each line, we can turn it into a list of tweets by splitting it at the end of line character. The file was originally created on a Mac, so the end of line character is an \n (think \n for new line). On a Windows computer, the end of line character is an \r\n (think \r for return and \n for new line). So if the file was created on a Windows computer, you might need to strip out the extra character with something like windows_file=windows_file.replace('\r','') before you split the lines, but you don’t need to worry about that here, no matter what operating system you are using. The end of line character comes from the computer that made the file, not the computer you are currently using. To split the tweets into a list: End of explanation """ len(tweets_list) """ Explanation: As always, you can check how many items are in the list: End of explanation """ for tweet in tweets_list[0:5]: print(tweet) """ Explanation: You can print the entire list by typing print(tweets_list), but it will be very long. A more useful way to look at it is to print just some of the items. Since it’s a list, we can loop through the first few item so they each print on the same line. End of explanation """ print(tweets_list[1:2]) """ Explanation: Note the new [0:5] after the tweets_list but before the : that begins the loop. The first number tells Python where to make the first cut in the list. The potentially counterintuitive part is that this number doesn’t reference an actual item in the list, but rather a position between each item in the list–think about where the comma goes when lists are created or printed. Adding to the confusion, the position at the start of the list is 0. So, in this case, we are telling Python we want to slice our list starting at the beginning and continuing until the fifth comma, which is after the fifth item in the list. So, if you wanted to just print the second item in the list, you could type: End of explanation """ print(tweets_list[1]) """ Explanation: OR End of explanation """ pos_sent = open("positive.txt").read() positive_words=pos_sent.split('\n') print(positive_words[:10]) """ Explanation: This slices the list from the first comma to the second comma, so the result is the second item in the list. Unless you have a computer science background, this may be confusing as it’s not the common way to think of items in lists. As a shorthand, you can leave out the first number in the pair if you want to start at the very beginning or leave out the last number if you want to go until the end. So, if you want to print out the first five tweets, you could just type print(tweet_list[:5]). There are several other shortcuts along these lines that are available. We will cover some of them in other tutorials. Now that we have our tweet list expanded, let’s load up the positive sentiment list and print out the first few entries: End of explanation """ for tweet in tweets_list: positive_counter=0 tweet_processed=tweet.lower() for p in punctuation: tweet_processed=tweet_processed.replace(p,'') words=tweet_processed.split(' ') for word in words: if word in positive_words: positive_counter=positive_counter+1 print(positive_counter/len(words)) """ Explanation: Like the tweet list, this file contained each entry on its own line, so it loads exactly the same way. If you typed len(positive_words) you would find out that this list has 2,230 entries. Preprocessing In the pre-class assignment, we explored how to preprocess the tweets: remove the punctuation, convert to lower case, and examine whether or not each word was in the positive sentiment list. We can use this exact same code here with our long list. The one alteration is that instead of having just one tweet, we now have a list of 1,365 tweets, so we have to loop over that list. End of explanation """ positive_counts=[] """ Explanation: Do the next part with your partner If you saw a string of numbers roll past you, it worked! To review, we start by looping over each item of the list. We set up a counter to hold the running total of the number of positive words found in the tweet. Then we make everything lower case and store it in tweet_processed. To strip out the punctuation, we loop over every item of punctuation, swapping out the punctuation mark with nothing. The cleaned tweet is then converted to a list of words, split at the white spaces. Finally, we loop through each word in the tweet, and if the word is in our new and expanded list of positive words, we increase the counter by one. After cycling through each of the tweet words, the proportion of positive words is computed and printed. The major problem with this script is that it is currently useless. It prints the positive sentiment results, but then doesn’t do anything with it. A more practical solution would be to store the results somehow. In a standard statistical package, we would generate a new variable that held our results. We can do something similar here by storing the results in a new list. Before we start the tweet loop, we add the line: End of explanation """ #Put your code here """ Explanation: Then, instead of printing the proportion, we can append it to the list using the following command: positive_counts.append(positive_counter/word_count) Step 1: make a list of counts. Copy and paste the above and rewrite it using the above append command. End of explanation """ len(positive_counts) """ Explanation: The next time we run through the loop, it shouldn't produce any output, but it will create a list of the proportions. Lets do a quick check to see how many positive words there are in the entire set of tweets: End of explanation """ #Put your code here """ Explanation: The next step is to plot a histogram of the data to see the distribution of positive texts: Step 2: make a histogram of the positive counts. End of explanation """ #Put your code here """ Explanation: Step 3: Subtract negative values. Now redo the caluclation in Step 1 but also subtract negative words (i.e. your measurement can now have a positive or negative value): End of explanation """ #Put your code here """ Explanation: Step 4: Generate positive/negative histogram. Generate a second histogram using range -5 to 5 and 20 bins. End of explanation """ only_positive=0; only_negative=0; both_pos_and_neg=0; neither_pos_nor_neg=0; #Put your code here. """ Explanation: Another way to model the "bag of words" is to evaluate if the tweet has only positive words, only negative words, both positive and negative words or neither positive nor negative words. Rewrite your code to keep track of all four totals. Step 5: Count "types" of tweets. Rewrite the code from steps 1 & 3 and determin if each tweet has only positive works, only negative words, both positive and negative words or neither positive nor negative words. Keep total counts the number of each kind of tweet. End of explanation """ #Run this code. It should output True. print(only_positive) print(only_negative) print(both_pos_and_neg) print(neither_pos_nor_neg) only_positive + only_negative + both_pos_and_neg + neither_pos_nor_neg == len(tweets_list) """ Explanation: Step 6: Check your answer. If everything went as planned, you should be able to add all four totals and it will be equal to the total number of tweets! End of explanation """ # The slices will be ordered and plotted counter-clockwise. labels = 'positive', 'both', 'negative', 'neither' sizes = [only_positive, both_pos_and_neg, only_negative, neither_pos_nor_neg] colors = ['yellowgreen', 'yellow','red', 'lightcyan'] explode = (0.1, 0, 0.1, 0) plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90); """ Explanation: Step 7: Make a Pie Graph of your results. Now we are just going to plot the results using matplotlib pie function. If you used the variables above this should just work. End of explanation """ from IPython.display import HTML HTML( """ <iframe src="https://goo.gl/forms/MEOZvOwBcY7CEfEj1?embedded=true" width="80%" height="1200px" frameborder="0" marginheight="0" marginwidth="0"> Loading... </iframe> """ ) """ Explanation: Assignment wrapup Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment! End of explanation """
PyPSA/PyPSA
examples/notebooks/transformer_example.ipynb
mit
import pypsa import numpy as np import pandas as pd network = pypsa.Network() network.add("Bus", "MV bus", v_nom=20, v_mag_pu_set=1.02) network.add("Bus", "LV1 bus", v_nom=0.4) network.add("Bus", "LV2 bus", v_nom=0.4) network.add( "Transformer", "MV-LV trafo", type="0.4 MVA 20/0.4 kV", bus0="MV bus", bus1="LV1 bus", ) network.add( "Line", "LV cable", type="NAYY 4x50 SE", bus0="LV1 bus", bus1="LV2 bus", length=0.1 ) network.add("Generator", "External Grid", bus="MV bus", control="Slack") network.add("Load", "LV load", bus="LV2 bus", p_set=0.1, q_set=0.05) def run_pf(): network.lpf() network.pf(use_seed=True) return pd.DataFrame( { "Voltage Angles": network.buses_t.v_ang.loc["now"] * 180.0 / np.pi, "Volate Magnitude": network.buses_t.v_mag_pu.loc["now"], } ) run_pf() network.transformers.tap_position = 2 run_pf() network.transformers.tap_position = -2 run_pf() """ Explanation: Transformer with non-trivial phase shift and tap ratio This example is a copy of pandapower's minimal example. End of explanation """ new_trafo_lv_tap = network.transformer_types.loc[["0.4 MVA 20/0.4 kV"]] new_trafo_lv_tap.index = ["New trafo"] new_trafo_lv_tap.tap_side = 1 new_trafo_lv_tap.T network.transformer_types = network.transformer_types.append(new_trafo_lv_tap) network.transformers.type = "New trafo" network.transformers.tap_position = 2 run_pf() network.transformers.T network.transformers.tap_position = -2 run_pf() """ Explanation: Now play with tap changer on LV side End of explanation """ network.generators.p_nom = 1.0 network.lines.s_nom = 1.0 network.lopf() pd.DataFrame( { "Voltage Angles": network.buses_t.v_ang.loc["now"] * 180.0 / np.pi, "Volate Magnitude": network.buses_t.v_mag_pu.loc["now"], } ) """ Explanation: Now make sure that the phase shift is also there in the LOPF End of explanation """
tpin3694/tpin3694.github.io
sql/sums_counts_max_averages.ipynb
mit
# Ignore %load_ext sql %sql sqlite:// %config SqlMagic.feedback = False """ Explanation: Title: Calculate Counts, Sums, Max, and Averages Slug: sums_counts_max_averages Summary: Calculate Counts, Sums, and Averages in SQL. Date: 2017-01-16 12:00 Category: SQL Tags: Basics Authors: Chris Albon Note: This tutorial was written using Catherine Devlin's SQL in Jupyter Notebooks library. If you have not using a Jupyter Notebook, you can ignore the two lines of code below and any line containing %%sql. Furthermore, this tutorial uses SQLite's flavor of SQL, your version might have some differences in syntax. For more, check out Learning SQL by Alan Beaulieu. End of explanation """ %%sql -- Create a table of criminals CREATE TABLE criminals (pid, name, age, sex, city, minor); INSERT INTO criminals VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1); INSERT INTO criminals VALUES (234, 'Bill James', 22, 'M', 'Santa Rosa', 0); INSERT INTO criminals VALUES (632, 'Stacy Miller', 23, 'F', 'San Francisco', 0); INSERT INTO criminals VALUES (901, 'Gordon Ado', 32, 'F', 'San Francisco', 0); INSERT INTO criminals VALUES (512, 'Bill Byson', 21, 'M', 'Petaluma', 0); """ Explanation: Create Data End of explanation """ %%sql -- Select name and average age, SELECT city, avg(age) -- from the table 'criminals', FROM criminals -- after grouping by city GROUP BY city """ Explanation: View Average Ages By City End of explanation """ %%sql -- Select name and average age, SELECT city, max(age) -- from the table 'criminals', FROM criminals -- after grouping by city GROUP BY city """ Explanation: View Max Age By City End of explanation """ %%sql -- Select name and average age, SELECT city, count(name) -- from the table 'criminals', FROM criminals -- after grouping by city GROUP BY city """ Explanation: View Count Of Criminals By City End of explanation """ %%sql -- Select name and average age, SELECT city, total(age) -- from the table 'criminals', FROM criminals -- after grouping by city GROUP BY city """ Explanation: View Total Age By City End of explanation """
rohithmohan/aesop
docs/barnase_barstar_directedmutagenesis.ipynb
gpl-3.0
from aesop import DirectedMutagenesis, plotScan_interactive, plotNetwork_interactive path_apbs = 'path\to\executable\apbs' path_coulomb = 'path\to\executable\coulomb' path_pdb2pqr = 'path\to\executable\pdb2pqr' jobname = 'directedscan' pdbfile = 'barnase_barstar.pdb' selstr = ['chain A', 'chain B'] target = ['resnum 27', 'resnum 73', 'resnum 83', 'resnum 87', # mutations in chain A 'resnum 145', 'resnum 149', 'resnum 164', 'resnum 186'] # mutations in chain B mutation = ['ASP', 'LYS', 'GLU', 'GLU', # mutations in chain A 'ARG', 'ARG', 'ASP', 'LYS'] # mutations in chain B mutscan = DirectedMutagenesis(pdb=pdbfile, pdb2pqr_exe=path_pdb2pqr, apbs_exe=path_apbs, coulomb_exe=path_coulomb, jobname=jobname, selstr=selstr, target=target, mutation=mutation, minim=True) mutscan.run() """ Explanation: Barnase-Barstar Directed Mutagenesis Interactive Plotting Demo This notebook showcases some of the interactive plotting functions plotScan_interactive and plotNetwork_interactive in AESOP using the Barnase-Barstar Directed Mutagenesis example.The sample code below imports the relevant classes and functions to perform user specified mutations and output the electrostatic analysis results using interactive plots. Before proceeding, make sure you have the python packages plotly and networkx installed as described in the documentation. End of explanation """ plotScan_interactive(mutscan,display_output='notebook') #If you are not using a notebook to run your code then use the code below instead: #plotScan_interactive(mutscan) """ Explanation: Once DirectedMutagenesis is instantiated and finished running, we can plot the results. The plotScan_interactive function by default, outputs the results in an html file and opens it up in your browser. However, if you are using a notebook to view it, you can display the plot inline by passing the argument display_output='notebook' to the function. Here we display it in the notebook so that it's easier to view alongside the code. End of explanation """ plotNetwork_interactive(mutscan,display_output='notebook') #If you are not using a notebook to run your code then use the code below instead: #plotNetwork_interactive(mutscan) """ Explanation: The plotScan_interactive function displays a bar plot similar to plotScan but now hovering over specific bars displays the corresponding asssociation/solvation free energy values. Additionally, clicking and dragging in the plot allows you to zoom in a subset of values. The plotly modebar in the top right has additional options such as zoom, autoscale and saving as a static image. plotNetwork_interactive provides similar functionality but for network plots. End of explanation """
ugaliguy/Udacity
data-analyst-nanodegree/dandp0-bikeshareanalysis/Bay_Area_Bike_Share_Analysis.ipynb
mit
# import all necessary packages and functions. # See this post to fix potential bug that arose the first time I tried to run this block # http://stackoverflow.com/questions/38085174/import-numpy-throws-error-syntaxerror-unicode-error-unicodeescape-codec #-ca/38107818#38107818 import csv from datetime import datetime import numpy as np import pandas as pd from babs_datacheck import question_3 from babs_visualizations import usage_stats, usage_plot from IPython.display import display %matplotlib inline # file locations file_in = '201402_trip_data.csv' file_out = '201309_trip_data.csv' with open(file_out, 'w') as f_out, open(file_in, 'r') as f_in: # set up csv reader and writer objects in_reader = csv.reader(f_in) out_writer = csv.writer(f_out) # write rows from in-file to out-file until specified date reached while True: datarow = next(in_reader) # trip start dates in 3rd column, m/d/yyyy HH:MM formats if datarow[2][:9] == '10/1/2013': break out_writer.writerow(datarow) """ Explanation: Bay Area Bike Share Analysis Introduction Tip: Quoted sections like this will provide helpful instructions on how to navigate and use an iPython notebook. Bay Area Bike Share is a company that provides on-demand bike rentals for customers in San Francisco, Redwood City, Palo Alto, Mountain View, and San Jose. Users can unlock bikes from a variety of stations throughout each city, and return them to any station within the same city. Users pay for the service either through a yearly subscription or by purchasing 3-day or 24-hour passes. Users can make an unlimited number of trips, with trips under thirty minutes in length having no additional charge; longer trips will incur overtime fees. In this project, you will put yourself in the shoes of a data analyst performing an exploratory analysis on the data. You will take a look at two of the major parts of the data analysis process: data wrangling and exploratory data analysis. But before you even start looking at data, think about some questions you might want to understand about the bike share data. Consider, for example, if you were working for Bay Area Bike Share: what kinds of information would you want to know about in order to make smarter business decisions? Or you might think about if you were a user of the bike share service. What factors might influence how you would want to use the service? Question 1: Write at least two questions you think could be answered by data. Answer: Which bike stations are the busiest? Break this down by most bikes unlocked and most bikes returned At what times are each of the bike stations at their busiest? What does ridership look like during the holidays? Tip: If you double click on this cell, you will see the text change so that all of the formatting is removed. This allows you to edit this block of text. This block of text is written using Markdown, which is a way to format text using headers, links, italics, and many other options. You will learn more about Markdown later in the Nanodegree Program. Hit Shift + Enter or Shift + Return. Using Visualizations to Communicate Findings in Data As a data analyst, the ability to effectively communicate findings is a key part of the job. After all, your best analysis is only as good as your ability to communicate it. In 2014, Bay Area Bike Share held an Open Data Challenge to encourage data analysts to create visualizations based on their open data set. You’ll create your own visualizations in this project, but first, take a look at the submission winner for Best Analysis from Tyler Field. Read through the entire report to answer the following question: Question 2: What visualizations do you think provide the most interesting insights? Are you able to answer either of the questions you identified above based on Tyler’s analysis? Why or why not? Answer: The most interesting visualization was the time-series graph showing the total daily rides by user. It's really nice to be able to choose whether you want to view all rides or rides by region. Having bars that highlight holidays and rainy days is also nice. I liked that you could also show the average number of rides too. This visualization doesn't help answer the first two questions, but it does help with the third question. Also, it prompts me to ask other questions (e.g. "what does ridership look like on rainy days?") Further down, the chart listing all stations (with BART in blue and Caltrain in red) does answer my first question. While I did see a bar chart for rides by the hour, there was no visualization which gave station specific data. So, my second question was not answered. Data Wrangling Now it's time to explore the data for yourself. Year 1 and Year 2 data from the Bay Area Bike Share's Open Data page have already been provided with the project materials; you don't need to download anything extra. The data comes in three parts: the first half of Year 1 (files starting 201402), the second half of Year 1 (files starting 201408), and all of Year 2 (files starting 201508). There are three main datafiles associated with each part: trip data showing information about each trip taken in the system (*_trip_data.csv), information about the stations in the system (*_station_data.csv), and daily weather data for each city in the system (*_weather_data.csv). When dealing with a lot of data, it can be useful to start by working with only a sample of the data. This way, it will be much easier to check that our data wrangling steps are working since our code will take less time to complete. Once we are satisfied with the way things are working, we can then set things up to work on the dataset as a whole. Since the bulk of the data is contained in the trip information, we should target looking at a subset of the trip data to help us get our bearings. You'll start by looking at only the first month of the bike trip data, from 2013-08-29 to 2013-09-30. The code below will take the data from the first half of the first year, then write the first month's worth of data to an output file. This code exploits the fact that the data is sorted by date (though it should be noted that the first two days are sorted by trip time, rather than being completely chronological). First, load all of the packages and functions that you'll be using in your analysis by running the first code cell below. Then, run the second code cell to read a subset of the first trip data file, and write a new file containing just the subset we are initially interested in. Tip: You can run a code cell like you formatted Markdown cells by clicking on the cell and using the keyboard shortcut Shift + Enter or Shift + Return. Alternatively, a code cell can be executed using the Play button in the toolbar after selecting it. While the cell is running, you will see an asterisk in the message to the left of the cell, i.e. In [*]:. The asterisk will change into a number to show that execution has completed, e.g. In [1]. If there is output, it will show up as Out [1]:, with an appropriate number to match the "In" number. End of explanation """ sample_data = pd.read_csv('201309_trip_data.csv') display(sample_data.head()) """ Explanation: Condensing the Trip Data The first step is to look at the structure of the dataset to see if there's any data wrangling we should perform. The below cell will read in the sampled data file that you created in the previous cell, and print out the first few rows of the table. End of explanation """ # Display the first few rows of the station data file. station_info = pd.read_csv('201402_station_data.csv') display(station_info.head()) # This function will be called by another function later on to create the mapping. def create_station_mapping(station_data): """ Create a mapping from station IDs to cities, returning the result as a dictionary. """ station_map = {} for data_file in station_data: with open(data_file, 'r') as f_in: # set up csv reader object - note that we are using DictReader, which # takes the first row of the file as a header row for each row's # dictionary keys weather_reader = csv.DictReader(f_in) for row in weather_reader: station_map[row['station_id']] = row['landmark'] return station_map """ Explanation: In this exploration, we're going to concentrate on factors in the trip data that affect the number of trips that are taken. Let's focus down on a few selected columns: the trip duration, start time, start terminal, end terminal, and subscription type. Start time will be divided into year, month, and hour components. We will also add a column for the day of the week and abstract the start and end terminal to be the start and end city. Let's tackle the lattermost part of the wrangling process first. Run the below code cell to see how the station information is structured, then observe how the code will create the station-city mapping. Note that the station mapping is set up as a function, create_station_mapping(). Since it is possible that more stations are added or dropped over time, this function will allow us to combine the station information across all three parts of our data when we are ready to explore everything. End of explanation """ def summarise_data(trip_in, station_data, trip_out): """ This function takes trip and station information and outputs a new data file with a condensed summary of major trip information. The trip_in and station_data arguments will be lists of data files for the trip and station information, respectively, while trip_out specifies the location to which the summarized data will be written. """ # generate dictionary of station - city mapping station_map = create_station_mapping(station_data) with open(trip_out, 'w') as f_out: # set up csv writer object out_colnames = ['duration', 'start_date', 'start_year', 'start_month', 'start_hour', 'weekday', 'start_city', 'end_city', 'subscription_type'] trip_writer = csv.DictWriter(f_out, fieldnames = out_colnames) trip_writer.writeheader() for data_file in trip_in: with open(data_file, 'r') as f_in: # set up csv reader object trip_reader = csv.DictReader(f_in) # collect data from and process each row for row in trip_reader: new_point = {} # convert duration units from seconds to minutes ### Question 3a: Add a mathematical operation below ### ### to convert durations from seconds to minutes. ### new_point['duration'] = float(row['Duration'])/60 # reformat datestrings into multiple columns ### Question 3b: Fill in the blanks below to generate ### ### the expected time values. ### trip_date = datetime.strptime(row['Start Date'], '%m/%d/%Y %H:%M') new_point['start_date'] = trip_date.strftime('%Y-%m-%d') new_point['start_year'] = trip_date.strftime('%Y') new_point['start_month'] = trip_date.strftime('%B') new_point['start_hour'] = trip_date.strftime('%H') new_point['weekday'] = trip_date.strftime('%A') # remap start and end terminal with start and end city new_point['start_city'] = station_map[row['Start Terminal']] new_point['end_city'] = station_map[row['End Terminal']] # two different column names for subscribers depending on file if 'Subscription Type' in row: new_point['subscription_type'] = row['Subscription Type'] else: new_point['subscription_type'] = row['Subscriber Type'] # write the processed information to the output file. trip_writer.writerow(new_point) """ Explanation: You can now use the mapping to condense the trip data to the selected columns noted above. This will be performed in the summarise_data() function below. As part of this function, the datetime module is used to parse the timestamp strings from the original data file as datetime objects (strptime), which can then be output in a different string format (strftime). The parsed objects also have a variety of attributes and methods to quickly obtain There are two tasks that you will need to complete to finish the summarise_data() function. First, you should perform an operation to convert the trip durations from being in terms of seconds to being in terms of minutes. (There are 60 seconds in a minute.) Secondly, you will need to create the columns for the year, month, hour, and day of the week. Take a look at the documentation for datetime objects in the datetime module. Find the appropriate attributes and method to complete the below code. End of explanation """ # Process the data by running the function we wrote above. station_data = ['201402_station_data.csv'] trip_in = ['201309_trip_data.csv'] trip_out = '201309_trip_summary.csv' summarise_data(trip_in, station_data, trip_out) # Load in the data file and print out the first few rows sample_data = pd.read_csv(trip_out) display(sample_data.head()) # Verify the dataframe by counting data points matching each of the time features. question_3(sample_data) """ Explanation: Question 3: Run the below code block to call the summarise_data() function you finished in the above cell. It will take the data contained in the files listed in the trip_in and station_data variables, and write a new file at the location specified in the trip_out variable. If you've performed the data wrangling correctly, the below code block will print out the first few lines of the dataframe and a message verifying that the data point counts are correct. End of explanation """ trip_data = pd.read_csv('201309_trip_summary.csv') usage_stats(trip_data) """ Explanation: Tip: If you save a jupyter Notebook, the output from running code blocks will also be saved. However, the state of your workspace will be reset once a new session is started. Make sure that you run all of the necessary code blocks from your previous session to reestablish variables and functions before picking up where you last left off. Exploratory Data Analysis Now that you have some data saved to a file, let's look at some initial trends in the data. Some code has already been written for you in the babs_visualizations.py script to help summarize and visualize the data; this has been imported as the functions usage_stats() and usage_plot(). In this section we'll walk through some of the things you can do with the functions, and you'll use the functions for yourself in the last part of the project. First, run the following cell to load the data, then use the usage_stats() function to see the total number of trips made in the first month of operations, along with some statistics regarding how long trips took. End of explanation """ usage_plot(trip_data, 'subscription_type') """ Explanation: You should see that there are over 27,000 trips in the first month, and that the average trip duration is larger than the median trip duration (the point where 50% of trips are shorter, and 50% are longer). In fact, the mean is larger than the 75% shortest durations. This will be interesting to look at later on. Let's start looking at how those trips are divided by subscription type. One easy way to build an intuition about the data is to plot it. We'll use the usage_plot() function for this. The second argument of the function allows us to count up the trips across a selected variable, displaying the information in a plot. The expression below will show how many customer and how many subscriber trips were made. Try it out! End of explanation """ usage_plot(trip_data, 'duration') """ Explanation: Seems like there's about 50% more trips made by subscribers in the first month than customers. Let's try a different variable now. What does the distribution of trip durations look like? End of explanation """ usage_plot(trip_data, 'duration', ['duration < 60']) """ Explanation: Looks pretty strange, doesn't it? Take a look at the duration values on the x-axis. Most rides are expected to be 30 minutes or less, since there are overage charges for taking extra time in a single trip. The first bar spans durations up to about 1000 minutes, or over 16 hours. Based on the statistics we got out of usage_stats(), we should have expected some trips with very long durations that bring the average to be so much higher than the median: the plot shows this in a dramatic, but unhelpful way. When exploring the data, you will often need to work with visualization function parameters in order to make the data easier to understand. Here's where the third argument of the usage_plot() function comes in. Filters can be set for data points as a list of conditions. Let's start by limiting things to trips of less than 60 minutes. End of explanation """ usage_plot(trip_data, 'duration', ['duration < 60'], boundary = 0, bin_width = 5) """ Explanation: This is looking better! You can see that most trips are indeed less than 30 minutes in length, but there's more that you can do to improve the presentation. Since the minimum duration is not 0, the left hand bar is slighly above 0. We want to be able to tell where there is a clear boundary at 30 minutes, so it will look nicer if we have bin sizes and bin boundaries that correspond to some number of minutes. Fortunately, you can use the optional "boundary" and "bin_width" parameters to adjust the plot. By setting "boundary" to 0, one of the bin edges (in this case the left-most bin) will start at 0 rather than the minimum trip duration. And by setting "bin_width" to 5, each bar will count up data points in five-minute intervals. End of explanation """ station_data = ['201402_station_data.csv', '201408_station_data.csv', '201508_station_data.csv' ] trip_in = ['201402_trip_data.csv', '201408_trip_data.csv', '201508_trip_data.csv' ] trip_out = 'babs_y1_y2_summary.csv' # This function will take in the station data and trip data and # write out a new data file to the name listed above in trip_out. summarise_data(trip_in, station_data, trip_out) """ Explanation: Question 4: Which five-minute trip duration shows the most number of trips? Approximately how many trips were made in this range? Answer: The duration between 5 and 10 minutes has the most number of trips. There were roughly 9000 trips of length between 5 to 10 minutes. Visual adjustments like this might be small, but they can go a long way in helping you understand the data and convey your findings to others. Performing Your Own Analysis Now that you've done some exploration on a small sample of the dataset, it's time to go ahead and put together all of the data in a single file and see what trends you can find. The code below will use the same summarise_data() function as before to process data. After running the cell below, you'll have processed all the data into a single data file. Note that the function will not display any output while it runs, and this can take a while to complete since you have much more data than the sample you worked with above. End of explanation """ trip_data = pd.read_csv('babs_y1_y2_summary.csv') display(trip_data.head()) """ Explanation: Since the summarise_data() function has created a standalone file, the above cell will not need to be run a second time, even if you close the notebook and start a new session. You can just load in the dataset and then explore things from there. End of explanation """ usage_stats(trip_data) # plot bike usage between Midnight and 5:00 AM usage_plot(trip_data,'start_hour', ['start_hour < 5'], boundary = 0, bin_width = 1) usage_plot(trip_data,'start_city') usage_stats(trip_data, ['start_city != "San Francisco"', 'end_city == "San Francisco']) usage_plot(trip_data, 'start_city', ['start_city != "San Francisco"', 'end_city == "San Francisco']) usage_plot(trip_data, 'subscription_type', ['start_city != "San Francisco"', 'end_city == "San Francisco']) usage_stats(trip_data, ['start_city == "San Francisco"', 'end_city != "San Francisco']) usage_plot(trip_data, 'end_city', ['start_city == "San Francisco"', 'end_city != "San Francisco']) usage_plot(trip_data, 'subscription_type', ['start_city == "San Francisco"', 'end_city != "San Francisco']) """ Explanation: Now it's your turn to explore the new dataset with usage_stats() and usage_plot() and report your findings! Here's a refresher on how to use the usage_plot() function: first argument (required): loaded dataframe from which data will be analyzed. second argument (required): variable on which trip counts will be divided. third argument (optional): data filters limiting the data points that will be counted. Filters should be given as a list of conditions, each element should be a string in the following format: '&lt;field&gt; &lt;op&gt; &lt;value&gt;' using one of the following operations: >, <, >=, <=, ==, !=. Data points must satisfy all conditions to be counted or visualized. For example, ["duration &lt; 15", "start_city == 'San Francisco'"] retains only trips that originated in San Francisco and are less than 15 minutes long. If data is being split on a numeric variable (thus creating a histogram), some additional parameters may be set by keyword. - "n_bins" specifies the number of bars in the resultant plot (default is 10). - "bin_width" specifies the width of each bar (default divides the range of the data by number of bins). "n_bins" and "bin_width" cannot be used simultaneously. - "boundary" specifies where one of the bar edges will be placed; other bar edges will be placed around that value (this may result in an additional bar being plotted). This argument may be used alongside the "n_bins" and "bin_width" arguments. You can also add some customization to the usage_stats() function as well. The second argument of the function can be used to set up filter conditions, just like how they are set up in usage_plot(). End of explanation """ usage_stats(trip_data, ['start_city != "San Francisco"', 'end_city == "San Francisco']) usage_stats(trip_data, ['start_city == "San Francisco"', 'end_city != "San Francisco']) # Final Plot 1 usage_plot(trip_data, 'start_city', ['start_city != "San Francisco"', 'end_city == "San Francisco']) """ Explanation: Explore some different variables using the functions above and take note of some trends you find. Feel free to create additional cells if you want to explore the dataset in other ways or multiple ways. Tip: In order to add additional cells to a notebook, you can use the "Insert Cell Above" and "Insert Cell Below" options from the menu bar above. There is also an icon in the toolbar for adding new cells, with additional icons for moving the cells up and down the document. By default, new cells are of the code type; you can also specify the cell type (e.g. Code or Markdown) of selected cells from the Cell menu or the dropdown in the toolbar. One you're done with your explorations, copy the two visualizations you found most interesting into the cells below, then answer the following questions with a few sentences describing what you found and why you selected the figures. Make sure that you adjust the number of bins or the bin limits so that they effectively convey data findings. Feel free to supplement this with any additional numbers generated from usage_stats() or place multiple visualizations to support your observations. End of explanation """ # Final Plot 2 # plot bike usage between Midnight and 5:00 AM usage_plot(trip_data,'start_hour', ['start_hour < 5'], boundary = 0, bin_width = 1) """ Explanation: Question 5a: What is interesting about the above visualization? Why did you select it? Answer: I was interested in determining how many trips started in one city and ended in a different one. I was not able to do this for all five cities at once. So, I focused on trips starting in San Francisco. The statistics are interesting. Of the 25 trips shown above, at least five of them had a duration greater than 11 hours (688.53 minutes/60 minutes > 11 hours). On the other hand, such trips not starting in San Francisco, tend be of shorter duration (on average slightly longer than 6 hours). In both cases, such trips were taken more by customers rather than subscribers. Judging by the durations of these rides, the customers must be wealthy enough to afford the extra charges. End of explanation """
agile-geoscience/xlines
notebooks/08_Read_and_write_LAS.ipynb
apache-2.0
import welly ls ../data/*.LAS """ Explanation: x lines of Python Reading and writing LAS files This notebook goes with the Agile blog post of 23 October. Set up a conda environment with: conda create -n welly python=3.6 matplotlib=2.0 scipy pandas You'll need welly in your environment: conda install tqdm # Should happen automatically but doesn't pip install welly This will also install the latest versions of striplog and lasio. End of explanation """ import lasio l = lasio.read('../data/P-129.LAS') # Line 1. """ Explanation: 1. Load the LAS file with lasio End of explanation """ l """ Explanation: That's it! But the object itself doesn't tell us much — it's really just a container: End of explanation """ l.header['Well'] # Line 2. """ Explanation: 2. Look at the WELL section of the header End of explanation """ l.header['Parameter']['EKB'] """ Explanation: You can go in and find the KB if you know what to look for: End of explanation """ l.data """ Explanation: 3. Look at the curve data The curves are all present one big NumPy array: End of explanation """ l.curves.GR # Line 3. """ Explanation: Or we can go after a single curve object: End of explanation """ l['GR'] # Line 4. """ Explanation: And there's a shortcut to its data: End of explanation """ import matplotlib.pyplot as plt plt.figure(figsize=(15,3)) plt.plot(l['DEPT'], l['GR']) plt.show() """ Explanation: ...so it's easy to make a plot against depth: End of explanation """ l.df().head() # Line 5. """ Explanation: 4. Inspect the curves as a pandas dataframe End of explanation """ from welly import Well w = Well.from_las('../data/P-129.LAS') # Line 6. """ Explanation: 5. Load the LAS file with welly End of explanation """ w """ Explanation: welly Wells know how to display some basics: End of explanation """ w.df().head() """ Explanation: And the Well object also has lasio's access to a pandas DataFrame: End of explanation """ gr = w.data['GR'] # Line 7. gr """ Explanation: 6. Look at welly's Curve object Like the Well, a Curve object can report a bit about itself: End of explanation """ gr.basis """ Explanation: One important thing about Curves is that each one knows its own depths — they are stored as a property called basis. (It's not actually stored, but computed on demand from the start depth, the sample interval (which must be constant for the whole curve) and the number of samples in the object.) End of explanation """ gr.to_basis(start=300, stop=1000).plot() # Line 8. """ Explanation: 7. Plot part of a curve We'll grab the interval from 300 m to 1000 m and plot it. End of explanation """ sm = gr.smooth(window_length=15, samples=False) # Line 9. sm.plot() """ Explanation: 8. Smooth a curve Curve objects are, fundamentally, NumPy arrays. But they have some extra tricks. We've already seen Curve.plot(). Using the Curve.smooth() method, we can easily smooth a curve, eg by 15 m (passing samples=True would smooth by 15 samples): End of explanation """ print("Data shape: {}".format(w.las.data.shape)) w.las.data """ Explanation: 9. Export a set of curves as a matrix You can get at all the data through the lasio l.data object: End of explanation """ w.data.keys() keys=['CALI', 'DT', 'DTS', 'RHOB', 'SP'] w.plot(tracks=['TVD']+keys) X, basis = w.data_as_matrix(keys=keys, start=275, stop=1850, step=0.5, return_basis=True) w.data['CALI'].shape """ Explanation: But we might want to do some other things, such as specify which curves you want (optionally using aliases like GR1, GRC, NGC, etc for GR), resample the data, or specify a start and stop depth — welly can do all this stuff. This method is also wrapped by Project.data_as_matrix() which is nice because it ensures that all the wells are exported at the same sample interval. Here are the curves in this well: End of explanation """ X.shape plt.figure(figsize=(15,3)) plt.plot(X.T[0]) plt.show() """ Explanation: So CALI had 12,718 points in it... since we downsampled to 0.5 m and removed the top and tail, we should have substantially fewer points: End of explanation """ w.location """ Explanation: 10+. BONUS: fix the lat, lon OK, we're definitely going to go over our budget on this one. Did you notice that the location of the well did not get loaded properly? End of explanation """ import re def transform_ll(text): """ Parses malformed lat and lon so they load properly. """ def callback(match): d = match.group(1).strip() m = match.group(2).strip() s = match.group(3).strip() c = match.group(4).strip() if c.lower() in ('w', 's') and d[0] != '-': d = '-' + d return ' '.join([d, m, s]) pattern = re.compile(r""".+?([-0-9]+?).? ?([0-9]+?).? ?([\.0-9]+?).? +?([NESW])""", re.I) text = pattern.sub(callback, text) return welly.utils.dms2dd([float(i) for i in text.split()]) """ Explanation: Let's look at some of the header: # LAS format log file from PETREL # Project units are specified as depth units #================================================================== ~Version information VERS. 2.0: WRAP. YES: #================================================================== ~WELL INFORMATION #MNEM.UNIT DATA DESCRIPTION #---- ------ -------------- ----------------------------- STRT .M 1.0668 :START DEPTH STOP .M 1939.13760 :STOP DEPTH STEP .M 0.15240 :STEP NULL . -999.25 :NULL VALUE COMP . Elmworth Energy Corporation :COMPANY WELL . Kennetcook #2 :WELL FLD . Windsor Block :FIELD LOC . Lat = 45* 12' 34.237" N :LOCATION PROV . Nova Scotia :PROVINCE UWI. Long = 63* 45'24.460 W :UNIQUE WELL ID LIC . P-129 :LICENSE NUMBER CTRY . CA :COUNTRY (WWW code) DATE. 10-Oct-2007 :LOG DATE {DD-MMM-YYYY} SRVC . Schlumberger :SERVICE COMPANY LATI .DEG :LATITUDE LONG .DEG :LONGITUDE GDAT . :GeoDetic Datum SECT . 45.20 Deg N :Section RANG . PD 176 :Range TOWN . 63.75 Deg W :Township Look at LOC and UWI. There are two problems: These items are in the wrong place. (Notice LATI and LONG are empty.) The items are malformed, with lots of extraneous characters. We can fix this in two steps: Remap the header items to fix the first problem. Parse the items to fix the second one. We'll define these in reverse because the remapping uses the transforming function. End of explanation """ print(transform_ll("""Lat = 45* 12' 34.237" N""")) remap = { 'LATI': 'LOC', # Use LOC for the parameter LATI. 'LONG': 'UWI', # Use UWI for the parameter LONG. 'LOC': None, # Use nothing for the parameter SECT. 'SECT': None, # Use nothing for the parameter SECT. 'RANG': None, # Use nothing for the parameter RANG. 'TOWN': None, # Use nothing for the parameter TOWN. } funcs = { 'LATI': transform_ll, # Pass LATI through this function before loading. 'LONG': transform_ll, # Pass LONG through it too. 'UWI': lambda x: "No UWI, fix this!" } w = Well.from_las('../data/P-129.LAS', remap=remap, funcs=funcs) w.location.latitude, w.location.longitude w.uwi """ Explanation: Make sure that works! End of explanation """
LeosNoob/PyNotes
PyNotes/7. Funciones.ipynb
gpl-3.0
printfunc(3) def func(num): return(num**num+num) """ Explanation: Funciones Las funciones es una fragmento de código que recibe parámetros, ejecuta instrucciones y regresa resultados. Y nos permiten reutilizar código llamandola cuantas veces sea necesario. ``` python def función(parámetros): instrucciones return(resultado) ``` Si una función es definida pero no invocada no se ejecutara en el código Parámetros Son elementos que recibe una función, para luego trabajar con ellos. Pueden ser: Variables, que se utilizan dentro del código de la función Constantes, valores predefinidos dentro de la función Nulos Se le entregan a la función al momento de llamarla. Se especifican al momento de definir la función Valor de retorno Es el valor que entrega la función una vez que ha terminado de ejecutarse, este se puede igualar a una variable dentro del programa ``` python var = función(parámetro_1,parámetro_2) ``` Invocación La invocación es el llamado de la función y se realiza cuando se quiere ejecutar la función definida. Para realizar una invocación es necesiario primero definir la función o importar el módulo que la contiene y luego llamarla. Si se intenta primero llamar a la función y luego definirla python regresara un error por definición. Modo incorrecto de invocar una función End of explanation """ def func(num): return(num**num+num) func(3) """ Explanation: Modo correcto de definir una función End of explanation """ alex=[90,70,80,60,90] kate=[60,70,90,70,90] david=[90,60,80,90,80] """ Explanation: Ejemplo de uso de funciónes Suponiendo que se tienen las siguientes listas que representan las calificaciones de 3 alumnos: End of explanation """ #Promedio para Alex i=0 sumatoria = 0 while i < len(alex): sumatoria += alex[i] i += 1 promedio=sumatoria/len(alex) print(promedio) #Promedio para Kate i=0 sumatoria = 0 while i < len(kate): sumatoria += kate[i] i += 1 promedio=sumatoria/len(kate) print(promedio) #Promedio para David i=0 sumatoria = 0 while i < len(david): sumatoria += david[i] i += 1 promedio=sumatoria/len(david) print(promedio) """ Explanation: y se desa calcular el promedio para cada uno, una forma de hacerlo seria la siguiente, calculando individualmente el promedio para cada uno e imprimiendo los resultados por pantalla: End of explanation """ def promedio(alumno): n = len(alumno) i = 0 sumatoria = 0 while i < n: sumatoria += alumno[i] i += 1 resultado= sumatoria/n print(resultado) """ Explanation: Pero como se puede apreciar eso complica el código haciendolo repetitivo y largo, la manera mas optima para hacer esto seria creando una función que calculara el promedio, para eso se utiliza la sintaxis: ``` python def función(parámetros): instrucciones return(resultado) ``` End of explanation """ promedio(alex) promedio(kate) promedio(david) """ Explanation: Ahora con la función promedio definida el código se puede simplificar de la siguiente manera End of explanation """ def saludo(): print("Hola!!!") saludo() """ Explanation: Parametros opcionales En este caso se pude definir una función sin necesidad de pasar parámetros End of explanation """ # Definicion de la función con el parámetro hora predeterminado como True def saludo(hora=True): if hora==True: print("Hola, buen día!") else: print("Hola, buenas noches") # Se ejecuta la función sin asignación de párametro saludo() # Se ejecuta la funcion con asignación de parámetro t=False saludo(t) """ Explanation: Parametros predefinidos En estos casos se le asigna un valor al predeterminado al párametro con el cual se ejecutara la función en caso de que no se le asigne algun otro valor. End of explanation """
dit/dit
examples/MDBSI.ipynb
bsd-3-clause
import numpy as np import matplotlib.pyplot as plt %matplotlib inline from dit import ditParams, Distribution from dit.distconst import uniform ditParams['repr.print'] = ditParams['print.exact'] = True """ Explanation: Multivariate Dependencies Beyond Shannon Information This is a companion Jupyter notebook to the work Multivariate Dependencies Beyond Shannon Information by Ryan G. James and James P. Crutchfield. This worksheet was written by Ryan G. James. It primarily makes use of the dit package for information theory calculations. Basic Imports We first import basic functionality. Further functionality will be imported as needed. End of explanation """ from dit.example_dists.mdbsi import dyadic, triadic dists = [('dyadic', dyadic), ('triadic', triadic)] """ Explanation: Distributions Here we define the two distributions to be compared. End of explanation """ from dit.profiles import ExtropyPartition, ShannonPartition def print_partition(dists, partition): ps = [str(partition(dist)).split('\n') for _, dist in dists ] print('\t' + '\t\t\t\t'.join(name for name, _ in dists)) for lines in zip(*ps): print('\t\t'.join(lines)) print_partition(dists, ShannonPartition) """ Explanation: I-Diagrams and X-Diagrams Here we construct the I- and X-Diagrams of both distributions. The I-Diagram is constructed by considering how the entropies of each variable interact. The X-Diagram is similar, but considers how the extropies of each variable interact. End of explanation """ print_partition(dists, ExtropyPartition) """ Explanation: Both I-Diagrams are the same. This implies that no Shannon measure (entropy, mutual information, conditional mutual information [including the transfer entropy], co-information, etc) can differentiate these patterns of dependency. End of explanation """ try: from prettytable import PrettyTable except ImportError: from pltable import PrettyTable from dit.multivariate import (entropy, coinformation, total_correlation, dual_total_correlation, independent_information, caekl_mutual_information, interaction_information, intrinsic_total_correlation, gk_common_information, wyner_common_information, exact_common_information, functional_common_information, mss_common_information, tse_complexity, ) from dit.other import (extropy, disequilibrium, perplexity, LMPR_complexity, renyi_entropy, tsallis_entropy, ) def print_table(title, table, dists): pt = PrettyTable(field_names = [''] + [name for name, _ in table]) for name, _ in table: pt.float_format[name] = ' 5.{0}'.format(3) for name, dist in dists: pt.add_row([name] + [measure(dist) for _, measure in table]) print("\n{}".format(title)) print(pt.get_string()) """ Explanation: Similarly, the X-Diagrams are identical and so no extropy-based measure can differentiate the distributions. Measures of Mutual and Common Information We now compute several measures of mutual and common information: End of explanation """ entropies = [('H', entropy), ('Renyi (α=2)', lambda d: renyi_entropy(d, 2)), ('Tsallis (q=2)', lambda d: tsallis_entropy(d, 2)), ] print_table('Entropies', entropies, dists) """ Explanation: Entropies Entropies generally capture the uncertainty contained in a distribution. Here, we compute the Shannon entropy, the Renyi entropy of order 2 (also known as the collision entropy), and the Tsallis entropy of order 2. Though we only compute the order 2 values, any order will produce values identical for both distributions. End of explanation """ mutual_informations = [('I', coinformation), ('T', total_correlation), ('B', dual_total_correlation), ('J', caekl_mutual_information), ('II', interaction_information), ] print_table('Mutual Informations', mutual_informations, dists) """ Explanation: The entropies for both distributions are indentical. This is not surprising: they have the same probability mass function. Mutual Informations Mutual informations are multivariate generalizations of the standard Shannon mutual information. By far, the most widely used (and often simply assumed to be the only) generalization is the total correlation, sometimes called the multi-information. It is defined as: $$ T[\mathbf{X}] = \sum H[X_i] - H[\mathbf{X}] = \sum p(\mathbf{x}) \log_2 \frac{p(\mathbf{x})}{p(x_1)p(x_2)\ldots p(x_n)} $$ Other generalizations exist, though, including the co-information, the dual total correlation, and the CAEKL mutual information. End of explanation """ common_informations = [('K', gk_common_information), ('C', lambda d: wyner_common_information(d, niter=1, polish=False)), ('G', lambda d: exact_common_information(d, niter=1, polish=False)), ('F', functional_common_information), ('M', mss_common_information), ] print_table('Common Informations', common_informations, dists) """ Explanation: The equivalence of all these generalizations is not surprising: Each of them can be defined as a function of the I-diagram, and so must be identical here. Common Informations Common informations are generally defined using an auxilliary random variable which captures some amount of information shared by the variables of interest. For all but the Gács-Körner common information, that shared information is the dual total correlation. End of explanation """ other_measures = [('IMI', lambda d: intrinsic_total_correlation(d, d.rvs[:-1], d.rvs[-1])), ('X', extropy), ('R', independent_information), ('P', perplexity), ('D', disequilibrium), ('LMRP', LMPR_complexity), ('TSE', tse_complexity), ] print_table('Other Measures', other_measures, dists) """ Explanation: As it turns out, only the Gács-Körner common information, K, distinguishes the two. Other Measures Here we list a variety of other information measures. End of explanation """ from dit.profiles import * def plot_profile(dists, profile): n = len(dists) plt.figure(figsize=(8*n, 6)) ent = max(entropy(dist) for _, dist in dists) for i, (name, dist) in enumerate(dists): ax = plt.subplot(1, n, i+1) profile(dist).draw(ax=ax) if profile not in [EntropyTriangle, EntropyTriangle2]: ax.set_ylim((-0.1, ent + 0.1)) ax.set_title(name) """ Explanation: Several other measures fail to differentiate our two distributions. For many of these (X, P, D, LMRP) this is because they are defined relative to the probability mass function. For the others, it is due to the equality of the I-diagrams. Only the intrinsic mutual information, IMI, can distinguish the two. Information Profiles Lastly, we consider several "profiles" of the information. End of explanation """ plot_profile(dists, ComplexityProfile) """ Explanation: Complexity Profile End of explanation """ plot_profile(dists, MUIProfile) """ Explanation: Once again, these two profiles are identical due to the I-Diagrams being identical. The complexity profile incorrectly suggests that there is no information at the scale of 3 variables. Marginal Utility of Information End of explanation """ plot_profile(dists, SchneidmanProfile) """ Explanation: The marginal utility of information is based on a linear programming problem with constrains related to values from the I-Diagram, and so here again the two distributions are undifferentiated. Connected Informations End of explanation """ plot_profile(dists, EntropyTriangle) """ Explanation: The connected informations are based on differences between maximum entropy distributions with differing $k$-way marginal distributions fixed. Here, the two distributions are differentiated Multivariate Entropy Triangle End of explanation """ from dit.pid.helpers import compare_measures for name, dist in dists: compare_measures(dist, name=name) """ Explanation: Both distributions are at an idential location in the multivariate entropy triangle. Partial Information We next consider a variety of partial information decompositions. End of explanation """ from itertools import product outcomes_a = [ (0,0,0,0), (0,2,3,2), (1,0,2,1), (1,2,1,3), (2,1,3,3), (2,3,0,1), (3,1,1,2), (3,3,2,0), ] outcomes_b = [ (0,0,0,0), (0,0,1,1), (0,1,0,1), (0,1,1,0), (1,0,0,1), (1,0,1,0), (1,1,0,0), (1,1,1,1), ] outcomes = [ tuple([2*a+b for a, b in zip(a_, b_)]) for a_, b_ in product(outcomes_a, outcomes_b) ] quadradic = uniform(outcomes) dyadic2 = uniform([(4*a+2*c+e, 4*a+2*d+f, 4*b+2*c+f, 4*b+2*d+e) for a, b, c, d, e, f in product([0,1], repeat=6)]) dists2 = [('dyadic2', dyadic2), ('quadradic', quadradic)] print_partition(dists2, ShannonPartition) print_partition(dists2, ExtropyPartition) print_table('Entropies', entropies, dists2) print_table('Mutual Informations', mutual_informations, dists2) print_table('Common Informations', common_informations, dists2) print_table('Other Measures', other_measures, dists2) plot_profile(dists2, ComplexityProfile) plot_profile(dists2, MUIProfile) plot_profile(dists2, SchneidmanProfile) plot_profile(dists2, EntropyTriangle) """ Explanation: Here we see that the PID determines that in dyadic distribution two random variables uniquely contribute a bit of information to the third, whereas in the triadic distribution two random variables redundantly influene the third with one bit, and synergistically with another. Multivariate Extensions End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/inm/cmip6/models/sandbox-3/atmoschem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'inm', 'sandbox-3', 'atmoschem') """ Explanation: ES-DOC CMIP6 Model Properties - Atmoschem MIP Era: CMIP6 Institute: INM Source ID: SANDBOX-3 Topic: Atmoschem Sub-Topics: Transport, Emissions Concentrations, Gas Phase Chemistry, Stratospheric Heterogeneous Chemistry, Tropospheric Heterogeneous Chemistry, Photo Chemistry. Properties: 84 (39 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:05 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Key Properties --&gt; Timestep Framework 4. Key Properties --&gt; Timestep Framework --&gt; Split Operator Order 5. Key Properties --&gt; Tuning Applied 6. Grid 7. Grid --&gt; Resolution 8. Transport 9. Emissions Concentrations 10. Emissions Concentrations --&gt; Surface Emissions 11. Emissions Concentrations --&gt; Atmospheric Emissions 12. Emissions Concentrations --&gt; Concentrations 13. Gas Phase Chemistry 14. Stratospheric Heterogeneous Chemistry 15. Tropospheric Heterogeneous Chemistry 16. Photo Chemistry 17. Photo Chemistry --&gt; Photolysis 1. Key Properties Key properties of the atmospheric chemistry 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmospheric chemistry model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of atmospheric chemistry model code. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.chemistry_scheme_scope') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "troposhere" # "stratosphere" # "mesosphere" # "mesosphere" # "whole atmosphere" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Chemistry Scheme Scope Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Atmospheric domains covered by the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.basic_approximations') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basic approximations made in the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.prognostic_variables_form') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "3D mass/mixing ratio for gas" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.5. Prognostic Variables Form Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Form of prognostic variables in the atmospheric chemistry component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.number_of_tracers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 1.6. Number Of Tracers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of advected tracers in the atmospheric chemistry model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.family_approach') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.7. Family Approach Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry calculations (not advection) generalized into families of species? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.coupling_with_chemical_reactivity') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 1.8. Coupling With Chemical Reactivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Atmospheric chemistry transport scheme turbulence is couple with chemical reactivity? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Software Properties Software properties of aerosol code 2.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Operator splitting" # "Integrated" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestep Framework Timestepping in the atmospheric chemistry model 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Mathematical method deployed to solve the evolution of a given variable End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_advection_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.2. Split Operator Advection Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemical species advection (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_physical_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.3. Split Operator Physical Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for physics (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_chemistry_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.4. Split Operator Chemistry Timestep Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for chemistry (in seconds). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_alternate_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 3.5. Split Operator Alternate Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 ? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 3.6. Integrated Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the atmospheric chemistry model (in seconds) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Explicit" # "Implicit" # "Semi-implicit" # "Semi-analytic" # "Impact solver" # "Back Euler" # "Newton Raphson" # "Rosenbrock" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 3.7. Integrated Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the type of timestep scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.turbulence') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Timestep Framework --&gt; Split Operator Order ** 4.1. Turbulence Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for turbulence scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.convection') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.2. Convection Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for convection scheme This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.precipitation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.3. Precipitation Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for precipitation scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.emissions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.4. Emissions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for emissions scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.5. Deposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for deposition scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.gas_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.6. Gas Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for gas phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.tropospheric_heterogeneous_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.7. Tropospheric Heterogeneous Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for tropospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.stratospheric_heterogeneous_phase_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.8. Stratospheric Heterogeneous Phase Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for stratospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.photo_chemistry') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.9. Photo Chemistry Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for photo chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.aerosols') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 4.10. Aerosols Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Call order for aerosols scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Key Properties --&gt; Tuning Applied Tuning methodology for atmospheric chemistry component 5.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview description of tuning: explain and motivate the main targets and metrics retained. &amp;Document the relative weight given to climate performance metrics versus process oriented metrics, &amp;and on the possible conflicts with parameterization level tuning. In particular describe any struggle &amp;with a parameter value that required pushing it to its limits to solve a particular model deficiency. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics of the global mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics of mean state used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics used in tuning model/component End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 6. Grid Atmospheric chemistry grid 6.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the atmopsheric chemistry grid End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.matches_atmosphere_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 6.2. Matches Atmosphere Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 * Does the atmospheric chemistry grid match the atmosphere grid?* End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7. Grid --&gt; Resolution Resolution in the atmospheric chemistry grid 7.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 7.2. Canonical Horizontal Resolution Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.number_of_horizontal_gridpoints') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.3. Number Of Horizontal Gridpoints Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Total number of horizontal (XY) points (or degrees of freedom) on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 7.4. Number Of Vertical Levels Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Number of vertical levels resolved on computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.grid.resolution.is_adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 7.5. Is Adaptive Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Default is False. Set true if grid resolution changes during execution. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Transport Atmospheric chemistry transport 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General overview of transport implementation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.use_atmospheric_transport') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 8.2. Use Atmospheric Transport Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is transport handled by the atmosphere, rather than within atmospheric cehmistry? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.transport.transport_details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.3. Transport Details Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If transport is handled within the atmospheric chemistry scheme, describe it. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9. Emissions Concentrations Atmospheric chemistry emissions 9.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview atmospheric chemistry emissions End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Vegetation" # "Soil" # "Sea surface" # "Anthropogenic" # "Biomass burning" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10. Emissions Concentrations --&gt; Surface Emissions ** 10.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of the chemical species emitted at the surface that are taken into account in the emissions scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Climatology" # "Spatially uniform mixing ratio" # "Spatially uniform concentration" # "Interactive" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10.2. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Methods used to define chemical species emitted directly into model layers above the surface (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed via a climatology, and the nature of the climatology (E.g. CO (monthly), C2H6 (constant)) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.4. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 10.6. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted at the surface and specified via any other method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.sources') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Aircraft" # "Biomass burning" # "Lightning" # "Volcanos" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11. Emissions Concentrations --&gt; Atmospheric Emissions TO DO 11.1. Sources Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Sources of chemical species emitted in the atmosphere that are taken into account in the emissions scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Climatology" # "Spatially uniform mixing ratio" # "Spatially uniform concentration" # "Interactive" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Methods used to define the chemical species emitted in the atmosphere (several methods allowed because the different species may not use the same method). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_climatology_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.3. Prescribed Climatology Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed via a climatology (E.g. CO (monthly), C2H6 (constant)) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_spatially_uniform_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.4. Prescribed Spatially Uniform Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and prescribed as spatially uniform End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.interactive_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.5. Interactive Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and specified via an interactive method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.other_emitted_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11.6. Other Emitted Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of chemical species emitted in the atmosphere and specified via an &quot;other method&quot; End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_lower_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12. Emissions Concentrations --&gt; Concentrations TO DO 12.1. Prescribed Lower Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the lower boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_upper_boundary') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 12.2. Prescribed Upper Boundary Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of species prescribed at the upper boundary. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 13. Gas Phase Chemistry Atmospheric chemistry transport 13.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview gas phase atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HOx" # "NOy" # "Ox" # "Cly" # "HSOx" # "Bry" # "VOCs" # "isoprene" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Species included in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_bimolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.3. Number Of Bimolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of bi-molecular reactions in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_termolecular_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.4. Number Of Termolecular Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of ter-molecular reactions in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_tropospheric_heterogenous_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.5. Number Of Tropospheric Heterogenous Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_stratospheric_heterogenous_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.6. Number Of Stratospheric Heterogenous Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_advected_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.7. Number Of Advected Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of advected species in the gas phase chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 13.8. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of gas phase species for which the concentration is updated in the chemical solver assuming photochemical steady state End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.interactive_dry_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.9. Interactive Dry Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.10. Wet Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet deposition included? Wet deposition describes the moist processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_oxidation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 13.11. Wet Oxidation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is wet oxidation included? Oxidation describes the loss of electrons or an increase in oxidation state by a molecule End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 14. Stratospheric Heterogeneous Chemistry Atmospheric chemistry startospheric heterogeneous chemistry 14.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview stratospheric heterogenous atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Cly" # "Bry" # "NOy" # TODO - please enter value(s) """ Explanation: 14.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Gas phase species included in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Polar stratospheric ice" # "NAT (Nitric acid trihydrate)" # "NAD (Nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particule))" # TODO - please enter value(s) """ Explanation: 14.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 14.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the stratospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.sedimentation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.5. Sedimentation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sedimentation is included in the stratospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 14.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the stratospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Tropospheric Heterogeneous Chemistry Atmospheric chemistry tropospheric heterogeneous chemistry 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview tropospheric heterogenous atmospheric chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.gas_phase_species') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Gas Phase Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List of gas phase species included in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.aerosol_species') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Sulphate" # "Nitrate" # "Sea salt" # "Dust" # "Ice" # "Organic" # "Black carbon/soot" # "Polar stratospheric ice" # "Secondary organic aerosols" # "Particulate organic matter" # TODO - please enter value(s) """ Explanation: 15.3. Aerosol Species Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Aerosol species included in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.number_of_steady_state_species') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.4. Number Of Steady State Species Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of steady state species in the tropospheric heterogeneous chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.interactive_dry_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.5. Interactive Dry Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.coagulation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 15.6. Coagulation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is coagulation is included in the tropospheric heterogeneous chemistry scheme or not? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 16. Photo Chemistry Atmospheric chemistry photo chemistry 16.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview atmospheric photo chemistry End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.number_of_reactions') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 16.2. Number Of Reactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of reactions in the photo-chemistry scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline (clear sky)" # "Offline (with clouds)" # "Online" # TODO - please enter value(s) """ Explanation: 17. Photo Chemistry --&gt; Photolysis Photolysis scheme 17.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Photolysis scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.environmental_conditions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 17.2. Environmental Conditions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any environmental conditions taken into account by the photolysis scheme (e.g. whether pressure- and temperature-sensitive cross-sections and quantum yields in the photolysis calculations are modified to reflect the modelled conditions.) End of explanation """
ProfessorKazarinoff/staticsite
content/code/matplotlib_plots/bar_plot_with_error_bars_jupyter_matplotlib.ipynb
gpl-3.0
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline data_url = 'https://github.com/ProfessorKazarinoff/staticsite/raw/master/content/code/matplotlib_plots/3D-printed_tensile_test_data.xlsx' df = pd.read_excel(data_url) df.head() #https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/US_Baby_Names/US_Baby_Names_right.csv """ Explanation: Engineers collect data and make conclusions based on the results. An important way to view results is with statistical charts. In this post we will build a bar chart that compares the tensile strength of 3D-printed ABS plastic under different printing conditions. We will add error bars to the chart to show the amount of uncertainty in the data. For this plot, the hieght of the bars represent the mean or average of the measured tensile stength in the sample of data. The error bars on the plot will represent +1/-1 standard deviation about the mean. The data we are going to plot is stored in an Microsoft Excel File. You can download the sample data here (clicking link will start the download): 3D-printed-tensile-bar-data.xlsx We'll use pandas to load the data into the notebook. I recommend that undergraduate engineers use the Anaconda distribution of Python, which comes with the pandas library already installed. If pandas is not available, open a terminal or the Anaconda Prompt and type: pip install pandas or ``` conda install pandas ``` Note that when I first tried to run the pd.read_excel() function, I was returned an error: ```python ImportError: Install xlrd >= 0.9.0 for Excel support ```` To solve this, I went to the Anaconda Prompt and typed: conda install xlrd Once the xlrd module was installed, the pd.read_excel() function worked just fine. To start the jupyter notebook, we need to import the required packages: pandas numpy matplotlib The %matplotlib inline magic command is add so that we can see our plots right in the jupyter notebook. End of explanation """ df['Tensile Strength (Mpa)'].describe() """ Explanation: Pandas has a nice little method to view the staticstics for column in our datafram called describe(). We'll use the describe() method to get a look at our basic statistics. The tensile strength column is the one we are interested in. Note the describe() method needs to include the () parenthesis at the end. End of explanation """ df['Tensile Strength (Mpa)'].groupby(df['Material']).describe() ABS_df = df[df['Material'] == 'ABS'] HIPS_df = df[df['Material'] == 'HIPS'] """ Explanation: This gives us the mean for the whole tensile strength column, but we are intrested in comparing the two materials, ABS and HIPS. HIPS stands for High-Impact PolyStyrene and is a common 3-D printing fillament material like ABS and PLA. We need a way to only group the ABS data together and group the HIPS data seperatly. We can view the statistics for the rows that are ABS data and the rows that are HIPS data seperatly using pandas groupby method. End of explanation """ ABS_mean = ABS_df['Tensile Strength (Mpa)'].mean() ABS_stdev = ABS_df['Tensile Strength (Mpa)'].std() HIPS_mean = HIPS_df['Tensile Strength (Mpa)'].mean() HIPS_stdev = HIPS_df['Tensile Strength (Mpa)'].std() """ Explanation: Let's save the mean (the average) and the std (standard deviation) to new variables End of explanation """ plt.bar(['ABS', 'HIPS'], [ABS_mean, HIPS_mean],yerr=[ABS_stdev, HIPS_stdev], capsize=10) plt.ylabel('Tensile Strength (MPa)') plt.title('Tensile Strength of 3-D Printed ABS Tensile Bars') plt.savefig('ABS_HIPS_plot_with_error_bars.png', dpi=300, bbox_inches='tight') plt.show() """ Explanation: Time to fire up the plot. We will build a plot using matplotlib. We'll use matplotlibs plt.bar method to build the plot. End of explanation """
SolitonScientific/AtomicString
AFAString.ipynb
mit
import numpy as np import pylab as pl pl.rcParams["figure.figsize"] = 9,6 ################################################################### ##This script calculates the values of Atomic Function up(x) (1971) ################################################################### ################### One Pulse of atomic function def up1(x: float) -> float: #Atomic function table up_y = [0.5, 0.48, 0.460000017,0.440000421,0.420003478,0.400016184, 0.380053256, 0.360139056, 0.340308139, 0.320605107,0.301083436, 0.281802850, 0.262826445, 0.244218000, 0.226041554, 0.208361009, 0.191239338, 0.174736305, 0.158905389, 0.143991189, 0.129427260, 0.115840866, 0.103044024, 0.9110444278e-01, 0.798444445e-01, 0.694444445e-01, 0.598444445e-01, 0.510444877e-01, 0.430440239e-01, 0.358409663e-01, 0.294282603e-01, 0.237911889e-01, 0.189053889e-01, 0.147363055e-01, 0.112393379e-01, 0.836100883e-02, 0.604155412e-02, 0.421800000e-02, 0.282644445e-02, 0.180999032e-02, 0.108343562e-02, 0.605106267e-03, 0.308138660e-03, 0.139055523e-03, 0.532555251e-04, 0.161841328e-04, 0.347816874e-05, 0.420576116e-05, 0.167693347e-07, 0.354008603e-10, 0] up_x = np.arange(0.5, 1.01, 0.01) res = 0. if ((x>=0.5) and (x<=1)): for i in range(len(up_x) - 1): if (up_x[i] >= x) and (x < up_x[i+1]): N1 = 1 - (x - up_x[i])/0.01 res = N1 * up_y[i] + (1 - N1) * up_y[i+1] return res return res ############### Atomic Function Pulse with width, shift and scale ############# def upulse(t: float, a = 1., b = 0., c = 1., d = 0.) -> float: x = (t - b)/a res = 0. if (x >= 0.5) and (x <= 1): res = up1(x) elif (x >= 0.0) and (x < 0.5): res = 1 - up1(1 - x) elif (x >= -1 and x <= -0.5): res = up1(-x) elif (x > -0.5) and (x < 0): res = 1 - up1(1 + x) res = d + res * c return res ############### Atomic Function Applied to list with width, shift and scale ############# def up(x: list, a = 1., b = 0., c = 1., d = 0.) -> list: res = [] for i in range(len(x)): res.append(upulse(x[i], a, b, c, d)) return res x = np.arange(-2.0, 2.0, 0.01) pl.title('Atomic Function up(x)') pl.plot(x, up(x), label='Atomic Function') pl.grid(True) pl.show() """ Explanation: <font color=Teal>ATOMIC and ASTRING FUNCTIONS (Python Code)</font> By Sergei Yu. Eremenko, PhD, Dr.Eng., Professor, Honorary Professor https://www.researchgate.net/profile/Sergei_Eremenko https://www.amazon.com/Sergei-Eremenko/e/B082F3MQ4L https://www.linkedin.com/in/sergei-eremenko-3862079 https://www.facebook.com/SergeiEremenko.Author Atomic functions (AF) described in many books and hundreds of papers have been discovered in 1970s by Academician NAS of Ukraine Rvachev V.L. (https://ru.wikipedia.org/w/index.php?oldid=83948367) (author's teacher) and professor Rvachev V.A. and advanced by many followers, notably professor Kravchenko V.F. (https://ru.wikipedia.org/w/index.php?oldid=84521570), H. Gotovac (https://www.researchgate.net/profile/Hrvoje_Gotovac), V.M. Kolodyazhni (https://www.researchgate.net/profile/Volodymyr_Kolodyazhny), O.V. Kravchenko (https://www.researchgate.net/profile/Oleg_Kravchenko) as well as the author S.Yu. Eremenko (https://www.researchgate.net/profile/Sergei_Eremenko) [1-4] for a wide range of applications in mathematical physics, boundary value problems, statistics, radio-electronics, telecommunications, signal processing, and others. As per historical survey (https://www.researchgate.net/publication/308749839), some elements, analogs, subsets or Fourier transformations of AFs sometimes named differently (Fabius function, hat function, compactly supported smooth function) have been probably known since 1930s and rediscovered many times by scientists from different countries, including Fabius, W.Hilberg and others. However, the most comprehensive 50+ years’ theory development supported by many books, dissertations, hundreds of papers, lecture courses and multiple online resources have been performed by the schools of V.L. Rvachev, V.A. Rvachev and V.F. Kravchenko. In 2017-2020, Sergei Yu. Eremenko, in papers "Atomic Strings and Fabric of Spacetime", "Atomic Solitons as a New Class of Solitons", "Atomic Machine Learning" and book "Soliton Nature" [1-8], has introduced <b>AString</b> atomic function as an integral and 'composing branch' of Atomic Function up(x): <font color=maroon>AString'(x) = AString(2x+1) - AString(2x-1) = up(x)</font> AString function, is a smooth solitonic kink function by joining of which on a periodic lattice it is possible to compose a straight-line resembling flat spacetime as well as to build 'solitonic atoms' composing different fields. It may lead to novel models of spacetime and quantized gravity where AString may describe Spacetime Quantum, or Spacetime Metriant. Also, representing of different fields via shift and stretches of AStrings and Atomic Functions may lead to unified theory where AString may describe some fundamental building block of quantum fields, like a string, elementary spacetime distortion or metriant. So, apart from traditional areas of AF applications in mathematical physics, radio-electronics and signal processing, AStrings and Atomic Functions may be expanded to Spacetime Physics, String theory, General and Special Relativity, Theory of Solitons, Lattice Physics, Quantized Gravity, Cosmology, Dark matter and Multiverse theories as well as Finite Element Methods, Nonarchimedean Computers, Atomic regression analysis, Atomic Kernels, Machine Learning and Artificial Intelligence. <font color=teal>1. Atomic Function up(x) (introduced in 1971 by V.L.Rvachev and V.A.Rvachev)</font> End of explanation """ ############### Atomic String ############# def AString1(x: float) -> float: res = 1 * (upulse(x/2.0 - 0.5) - 0.5) return res ############### Atomic String Pulse with width, shift and scale ############# def AStringPulse(t: float, a = 1., b = 0., c = 1., d = 0.) -> float: x = (t - b)/a if (x < -1): res = -0.5 elif (x > 1): res = 0.5 else: res = AString1(x) res = d + res * c return res ###### Atomic String Applied to list with width, shift and scale ############# def AString(x: list, a = 1., b = 0., c = 1., d = 0.) -> list: res = [] for i in range(len(x)): res.append(AStringPulse(x[i], a, b, c, d)) #res[i] = AStringPulse(x[i], a, b, c) return res ###### Summation of two lists ############# def Sum(x1: list, x2: list) -> list: res = [] for i in range(len(x1)): res.append(x1[i] + x2[i]) return res x = np.arange(-2.0, 2.0, 0.01) pl.title('Atomic String Function') pl.plot(x, AString(x, 1.0, 0, 1, 0), label='Atomic String') pl.grid(True) pl.show() """ Explanation: <font color=teal>2. Atomic String Function (AString) is an Integral and Composing Branch of Atomic Function up(x) (introduced in 2017 by S. Yu. Eremenko)</font> AString function is solitary kink function which simultaneously is integral and composing branch of atomic function up(x) <font color=maroon>AString'(x) = AString(2x+1) - AString(2x-1) = up(x)</font> End of explanation """ x = np.arange(-2.0, 2.0, 0.01) #This Calculates Derivative dx = x[1] - x[0] dydx = np.gradient(up(x), dx) pl.plot(x, up(x), label='Atomic Function') pl.plot(x, AString(x, 1.0, 0, 1, 0), linewidth=2, label='Atomic String Function') pl.plot(x, dydx, '--', label='A-Function Derivative') pl.title('Atomic and AString Functions') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: Atomic String, Atomic Function (AF) and AF Derivative plotted together End of explanation """ x = np.arange(-2.0, 2.0, 0.01) pl.plot(x, up(x), label='Atomic Function', linewidth=2) pl.plot(x, dydx, '--', label='Atomic Function Derivative', linewidth=1, color="Green") pl.title('Atomic Function and Its Derivative') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: <font color=teal>3. Properties of Atomic Function Up(x)</font> 3.1. Atomic Function Derivative expressed via Atomic Function itself Atomic Function Derivative can be exressed via Atomic Function itself - up'(x)= 2up(2x+1)-2up(2x-1) meaning the shape of pulses for derivative function can be represented by shifted and stratched Atomic Function itself - remarkable property <font color=maroon>up'(x)= 2up(2x+1)-2up(2x-1)</font> Atomic Function and its Derivative plotted together End of explanation """ x = np.arange(-2.0, 2.0, 0.01) pl.plot(x, up(x, 1, -1), '--', linewidth=1, label='Atomic Function at x=-1') pl.plot(x, up(x, 1, +0), '--', linewidth=1, label='Atomic Function at x=0') pl.plot(x, up(x, 1, -1), '--', linewidth=1, label='Atomic Function at x=-1') pl.plot(x, Sum(up(x, 1, -1), Sum(up(x), up(x, 1, 1))), linewidth=2, label='Atomic Function Compounding') pl.title('Atomic Function Compounding represent 1') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: 3.2. Partition of Unity The Atomic Function pulses superposition set at points -2, -1, 0, +1, +2... can exactly represent a Unity (number 1): 1 = ... up(x-3) + up(x-2) + up(x-1) + up(x-0) + up(x+1) + up(x+2) + up(x+3) + ... <font color=maroon>1 = ... up(x-3) + up(x-2) + up(x-1) + up(x-0) + up(x+1) + up(x+2) + up(x+3) + ...</font> End of explanation """ x = np.arange(-5.0, 5.0, 0.01) pl.plot(x, up(x), label='Atomic Function', linewidth=2) #pl.plot(x, dydx, '--', label='Atomic Function Derivative', linewidth=1, color="Green") pl.title('Atomic Function is compactly supported') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: 3.3. Atomic Function (AF) is a 'finite', 'compactly supported', or 'solitary' function Like a Spline, Atomic Function (AF) 'compactly supported' not equal to zero only on section |x|<=1 End of explanation """ ######### Presentation of Atomic Function via Atomic Strings ########## x = np.arange(-2.0, 2.0, 0.01) pl.plot(x, AString(x, 1, 0, 1, 0), '--', linewidth=1, label='AString(x)') pl.plot(x, AString(x, 0.5, -0.5, +1, 0), '--', linewidth=2, label='+AString(2x+1)') pl.plot(x, AString(x, 0.5, +0.5, -1, 0), '--', linewidth=2, label='-AString(2x-1)') #pl.plot(x, up(x, 1.0, 0, 1, 0), '--', linewidth=1, label='Atomic Function') AS2 = Sum(AString(x, 0.5, -0.5, +1, 0), AString(x, 0.5, +0.5, -1, 0)) pl.plot(x, AS2, linewidth=3, label='Up(x) via Strings') pl.title('Atomic Function as a Combination of AStrings') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: 3.4 Atomic Function is a non-analytical function (can not be represented by Taylor's series), but with known Fourier Transformation allowing to exactly calculate AF in certain points, with tabular representation provided in script above. <font color=teal>4. Properties of Atomic String Function</font> 4.1. AString is not only Integral but also Composing Branch of Atomic Function <font color=maroon>AString'(x) = AString(2x+1) - AString(2x-1) = up(x)</font> Astring is a swing-like function - Integral of Atomic Function (AF) which can be expressed via AF itself: AString(x) = Integral(0,x)(Up(x)) = Up(x/2 - 1/2) - 1/2 <font color=maroon>AString(x) = Integral(0,x)(Up(x)) = Up(x/2 - 1/2) - 1/2</font> 4.2. Atomic Function is a 'solitonic atom' composed from two opposite AStrings The concept of 'Solitonic Atoms' (bions) composed from opposite kinks is known in soliton theory [3,5]. <font color=maroon>up(x) = AString(2x + 1) - AString(2x - 1)</font> End of explanation """ x = np.arange(-2, 2.0, 0.01) pl.title('AString and Fabius Functions') pl.plot(x, AString(x, 0.5, 0.5, 1, 0.5), label='Fabius Function') pl.plot(x, AString(x, 1, 0, 1, 0), label='AString Function') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: 4.3. AStrings and Atomic Solitons Solitonic mathematical properties of AString and Atomic Functions have been explored in author's paper [3] (Eremenko, S.Yu. Atomic solitons as a new class of solitons; 2018; https://www.researchgate.net/publication/329465767). They both satisfy differential equations with shifted arguments which introduce special kind of <b>nonlinearity</b> typical for all mathematical solitons. AString belong to the class of <b>Solitonic Kinks</b> similar to sine-Gordon, Frenkel-Kontorova, tanh and others. Unlike other kinks, AStrings are truly solitary (compactly-supported) and also have a unique property of composing of both straight-line and solitonic atoms on lattice resembling particle-like properties of solitons. Atomic Function up(x) is not actually a mathematical soliton, but a complex object composed from summation of two opposite AString kinks, and in solitonic terminology, is called 'solitonic atoms' (like bions). 4.4. All derivatives of AString can be represented via AString itself <font color=maroon>AString'(x) = AString(2x + 1) - AString(2x - 1)</font> It means AString is a smooth (infinitely divisible) function, with fractalic properties. 4.5. AString and Fabius Function Fabius Function https://en.wikipedia.org/wiki/Fabius_function, with unique property f'(x) = 2f(2x), published in 1966 but was probably known since 1935, is shifted and stretched AString function. Fabius function is not directly an integral of atomic function up(x). <font color=maroon>Fabius(x) = AString(2x - 1) + 0.5</font> End of explanation """ x = np.arange(-3, 3, 0.01) pl.plot(x, AString(x, 1, -1.0, 1, 0), '--', linewidth=1, label='AString 1') pl.plot(x, AString(x, 1, +0.0, 1, 0), '--', linewidth=1, label='AString 2') pl.plot(x, AString(x, 1, +1.0, 1, 0), '--', linewidth=1, label='AString 3') AS2 = Sum(AString(x, 1, -1.0, 1, 0), AString(x, 1, +0.0, 1, 0)) AS3 = Sum(AS2, AString(x, 1, +1.0, 1, 0)) pl.plot(x, AS3, label='AStrings Sum', linewidth=2) pl.title('Atomic Strings compose Line') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: 4.6. Partition of Line from Atomic String functions Combination/summation of Atomic Strings can exactly represent a straight line: x = ...Astring(x-2) + Astring(x-1) + AString(x) + Astring(x+1) + Astring(x+2)... <font color=maroon>x = ...Astring(x-2) + Astring(x-1) + AString(x) + Astring(x+1) + Astring(x+2)...</font> Partition based on AString function with width 1 and height 1 End of explanation """ x = np.arange(-40.0, 40.0, 0.01) width = 10.0 height = 10.0 #pl.plot(x, ABline (x, 1, 0), label='ABLine 1*x') pl.plot(x, AString(x, width, -3*width/2, height, -3*width/2), '--', linewidth=1, label='AString 1') pl.plot(x, AString(x, width, -1*width/2, height, -1*width/2), '--', linewidth=1, label='AString 2') pl.plot(x, AString(x, width, +1*width/2, height, +1*width/2), '--', linewidth=1, label='AString 3') pl.plot(x, AString(x, width, +3*width/2, height, +3*width/2), '--', linewidth=1, label='AString 4') AS2 = Sum(AString(x, width, -3*width/2, height, -3*width/2), AString(x, width, -1*width/2, height, -1*width/2)) AS3 = Sum(AS2, AString(x, width,+1*width/2, height, +1*width/2)) AS4 = Sum(AS3, AString(x, width,+3*width/2, height, +3*width/2)) pl.plot(x, AS4, label='AStrings Joins', linewidth=2) pl.title('Atomic Strings Combinations') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: Partition based on AString with certain width and height depending on a size of 'quanta' End of explanation """ x = np.arange(-50.0, 50.0, 0.1) dx = x[1] - x[0] CS6 = Sum(up(x, 5, -30, 5, 5), up(x, 15, 0, 15, 5)) CS6 = Sum(CS6, up(x, 10, +30, 10, 5)) pl.plot(x, CS6, label='Spacetime Density distribution') IntC6 = np.cumsum(CS6)*dx/50 pl.plot(x, IntC6, label='Spacetime Shape (Geodesics)') DerC6 = np.gradient(CS6, dx) pl.plot(x, DerC6, label='Spacetime Curvature') LightTrajectory = -10 -IntC6/5 pl.plot(x, LightTrajectory, label='Light Trajectory') pl.title('Shape of Curved Spacetime model') pl.legend(loc='best', numpoints=1) pl.grid(True) pl.show() """ Explanation: 5. Representing curved shapes via AStrings and Atomic Functions Shifts and stretches of Atomic adn AString functions allows reproducing curved surfaces (eq curved spacetime). Details are in author's papers "Atomic Strings and Fabric of Spacetime", "Atomic Solitons as a New Class of Solitons". End of explanation """ #pl.rcParams["figure.figsize"] = 16,12 book = pl.imread('BookSpread_small.png') pl.imshow(book) """ Explanation: <font color=teal>6. 'Soliton Nature' book</font> 6.1. AStrings and Atomic functions are also described in the book 'Soliton Nature' Soliton Nature book is easy-to-read, pictorial, interactive book which uses beautiful photography, video channel, and computer scripts in R and Python to demonstrate existing and explore new solitons – the magnificent and versatile energy concentration phenomenon of nature. New class of atomic solitons can be used to describe Higgs boson (‘the god particle’) fields, spacetime quanta and other fundamental building blocks of nature. End of explanation """
bgalbraith/bandits
notebooks/Stochastic Bandits - Preference Estimation.ipynb
apache-2.0
%matplotlib inline import os import sys module_path = os.path.abspath(os.path.join('..')) if module_path not in sys.path: sys.path.append(module_path) import bandits as bd """ Explanation: Stochastic Multi-Armed Bandits - Preference Estimation These examples come from Chapter 2 of Reinforcement Learning: An Introduction by Sutton and Barto (2nd ed. rev: Oct2015) End of explanation """ n_arms = 10 bandit = bd.GaussianBandit(n_arms, mu=4) n_trials = 1000 n_experiments = 500 """ Explanation: Instead of estimating the expected reward from selecting a particular arm, we may only care about the relative preference of one arm to another. End of explanation """ policy = bd.SoftmaxPolicy() agents = [ bd.GradientAgent(bandit, policy, alpha=0.1), bd.GradientAgent(bandit, policy, alpha=0.4), bd.GradientAgent(bandit, policy, alpha=0.1, baseline=False), bd.GradientAgent(bandit, policy, alpha=0.4, baseline=False) ] env = bd.Environment(bandit, agents, 'Gradient Agents') scores, optimal = env.run(n_trials, n_experiments) env.plot_results(scores, optimal) """ Explanation: Softmax Preference learning uses a Softmax-based policy, where the action estimates are converted to a probability distribution using the softmax function. This is then sampled to produce the chosen arm. End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/test-institute-1/cmip6/models/sandbox-3/atmos.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-1', 'sandbox-3', 'atmos') """ Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: TEST-INSTITUTE-1 Source ID: SANDBOX-3 Topic: Atmos Sub-Topics: Dynamical Core, Radiation, Turbulence Convection, Microphysics Precipitation, Cloud Scheme, Observation Simulation, Gravity Waves, Solar, Volcanos. Properties: 156 (127 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:43 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation """ # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) """ Explanation: Document Authors Set document authors End of explanation """ # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) """ Explanation: Document Contributors Specify document contributors End of explanation """ # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) """ Explanation: Document Publication Specify document publication status End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: Document Table of Contents 1. Key Properties --&gt; Overview 2. Key Properties --&gt; Resolution 3. Key Properties --&gt; Timestepping 4. Key Properties --&gt; Orography 5. Grid --&gt; Discretisation 6. Grid --&gt; Discretisation --&gt; Horizontal 7. Grid --&gt; Discretisation --&gt; Vertical 8. Dynamical Core 9. Dynamical Core --&gt; Top Boundary 10. Dynamical Core --&gt; Lateral Boundary 11. Dynamical Core --&gt; Diffusion Horizontal 12. Dynamical Core --&gt; Advection Tracers 13. Dynamical Core --&gt; Advection Momentum 14. Radiation 15. Radiation --&gt; Shortwave Radiation 16. Radiation --&gt; Shortwave GHG 17. Radiation --&gt; Shortwave Cloud Ice 18. Radiation --&gt; Shortwave Cloud Liquid 19. Radiation --&gt; Shortwave Cloud Inhomogeneity 20. Radiation --&gt; Shortwave Aerosols 21. Radiation --&gt; Shortwave Gases 22. Radiation --&gt; Longwave Radiation 23. Radiation --&gt; Longwave GHG 24. Radiation --&gt; Longwave Cloud Ice 25. Radiation --&gt; Longwave Cloud Liquid 26. Radiation --&gt; Longwave Cloud Inhomogeneity 27. Radiation --&gt; Longwave Aerosols 28. Radiation --&gt; Longwave Gases 29. Turbulence Convection 30. Turbulence Convection --&gt; Boundary Layer Turbulence 31. Turbulence Convection --&gt; Deep Convection 32. Turbulence Convection --&gt; Shallow Convection 33. Microphysics Precipitation 34. Microphysics Precipitation --&gt; Large Scale Precipitation 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics 36. Cloud Scheme 37. Cloud Scheme --&gt; Optical Cloud Properties 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution 40. Observation Simulation 41. Observation Simulation --&gt; Isscp Attributes 42. Observation Simulation --&gt; Cosp Attributes 43. Observation Simulation --&gt; Radar Inputs 44. Observation Simulation --&gt; Lidar Inputs 45. Gravity Waves 46. Gravity Waves --&gt; Orographic Gravity Waves 47. Gravity Waves --&gt; Non Orographic Gravity Waves 48. Solar 49. Solar --&gt; Solar Pathways 50. Solar --&gt; Solar Constant 51. Solar --&gt; Orbital Parameters 52. Solar --&gt; Insolation Ozone 53. Volcanos 54. Volcanos --&gt; Volcanoes Treatment 1. Key Properties --&gt; Overview Top level key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of atmosphere model code (CAM 4.0, ARPEGE 3.2,...) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_family') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "AGCM" # "ARCM" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.3. Model Family Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of atmospheric model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.basic_approximations') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "primitive equations" # "non-hydrostatic" # "anelastic" # "Boussinesq" # "hydrostatic" # "quasi-hydrostatic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Basic approximations made in the atmosphere. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.horizontal_resolution_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2. Key Properties --&gt; Resolution Characteristics of the model resolution 2.1. Horizontal Resolution Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of the model grid, e.g. T42, N48. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.2. Canonical Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Expression quoted for gross comparisons of resolution, e.g. 2.5 x 3.75 degrees lat-lon. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.range_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 2.3. Range Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Range of horizontal resolution with spatial details, eg. 1 deg (Equator) - 0.5 deg End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 2.4. Number Of Vertical Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of vertical levels resolved on the computational grid. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.high_top') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 2.5. High Top Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the atmosphere have a high-top? High-Top atmospheres have a fully resolved stratosphere with a model top above the stratopause. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_dynamics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3. Key Properties --&gt; Timestepping Characteristics of the atmosphere model time stepping 3.1. Timestep Dynamics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the dynamics, e.g. 30 min. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_shortwave_radiative_transfer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.2. Timestep Shortwave Radiative Transfer Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for the shortwave radiative transfer, e.g. 1.5 hours. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_longwave_radiative_transfer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 3.3. Timestep Longwave Radiative Transfer Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for the longwave radiative transfer, e.g. 3 hours. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.orography.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "present day" # "modified" # TODO - please enter value(s) """ Explanation: 4. Key Properties --&gt; Orography Characteristics of the model orography 4.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of the orography. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.orography.changes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "related to ice sheets" # "related to tectonics" # "modified mean" # "modified variance if taken into account in model (cf gravity waves)" # TODO - please enter value(s) """ Explanation: 4.2. Changes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N If the orography type is modified describe the time adaptation changes. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 5. Grid --&gt; Discretisation Atmosphere grid discretisation 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of grid discretisation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "spectral" # "fixed grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6. Grid --&gt; Discretisation --&gt; Horizontal Atmosphere discretisation in the horizontal 6.1. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "finite elements" # "finite volumes" # "finite difference" # "centered finite difference" # TODO - please enter value(s) """ Explanation: 6.2. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "second" # "third" # "fourth" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.3. Scheme Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation function order End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.horizontal_pole') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "filter" # "pole rotation" # "artificial island" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.4. Horizontal Pole Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal discretisation pole singularity treatment End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.grid_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Gaussian" # "Latitude-Longitude" # "Cubed-Sphere" # "Icosahedral" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 6.5. Grid Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal grid type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.vertical.coordinate_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "isobaric" # "sigma" # "hybrid sigma-pressure" # "hybrid pressure" # "vertically lagrangian" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 7. Grid --&gt; Discretisation --&gt; Vertical Atmosphere discretisation in the vertical 7.1. Coordinate Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Type of vertical coordinate system End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8. Dynamical Core Characteristics of the dynamical core 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of atmosphere dynamical core End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 8.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the dynamical core of the model. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.timestepping_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Adams-Bashforth" # "explicit" # "implicit" # "semi-implicit" # "leap frog" # "multi-step" # "Runge Kutta fifth order" # "Runge Kutta second order" # "Runge Kutta third order" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.3. Timestepping Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestepping framework type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "surface pressure" # "wind components" # "divergence/curl" # "temperature" # "potential temperature" # "total water" # "water vapour" # "water liquid" # "water ice" # "total water moments" # "clouds" # "radiation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 8.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of the model prognostic variables End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_boundary_condition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "sponge layer" # "radiation boundary condition" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 9. Dynamical Core --&gt; Top Boundary Type of boundary layer at the top of the model 9.1. Top Boundary Condition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary condition End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_heat') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.2. Top Heat Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary heat treatment End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_wind') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 9.3. Top Wind Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary wind treatment End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.lateral_boundary.condition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "sponge layer" # "radiation boundary condition" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 10. Dynamical Core --&gt; Lateral Boundary Type of lateral boundary condition (if the model is a regional model) 10.1. Condition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Type of lateral boundary condition End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 11. Dynamical Core --&gt; Diffusion Horizontal Horizontal diffusion scheme 11.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal diffusion scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "iterated Laplacian" # "bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 11.2. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal diffusion scheme method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Heun" # "Roe and VanLeer" # "Roe and Superbee" # "Prather" # "UTOPIA" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12. Dynamical Core --&gt; Advection Tracers Tracer advection scheme 12.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Tracer advection scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_characteristics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Eulerian" # "modified Euler" # "Lagrangian" # "semi-Lagrangian" # "cubic semi-Lagrangian" # "quintic semi-Lagrangian" # "mass-conserving" # "finite volume" # "flux-corrected" # "linear" # "quadratic" # "quartic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.2. Scheme Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Tracer advection scheme characteristics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conserved_quantities') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "dry mass" # "tracer mass" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.3. Conserved Quantities Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Tracer advection scheme conserved quantities End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conservation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "conservation fixer" # "Priestley algorithm" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 12.4. Conservation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracer advection scheme conservation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "VanLeer" # "Janjic" # "SUPG (Streamline Upwind Petrov-Galerkin)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13. Dynamical Core --&gt; Advection Momentum Momentum advection scheme 13.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Momentum advection schemes name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_characteristics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "2nd order" # "4th order" # "cell-centred" # "staggered grid" # "semi-staggered grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.2. Scheme Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Momentum advection scheme characteristics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_staggering_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Arakawa B-grid" # "Arakawa C-grid" # "Arakawa D-grid" # "Arakawa E-grid" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.3. Scheme Staggering Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Momentum advection scheme staggering type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conserved_quantities') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Angular momentum" # "Horizontal momentum" # "Enstrophy" # "Mass" # "Total energy" # "Vorticity" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.4. Conserved Quantities Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Momentum advection scheme conserved quantities End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conservation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "conservation fixer" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 13.5. Conservation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Momentum advection scheme conservation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.aerosols') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "sulphate" # "nitrate" # "sea salt" # "dust" # "ice" # "organic" # "BC (black carbon / soot)" # "SOA (secondary organic aerosols)" # "POM (particulate organic matter)" # "polar stratospheric ice" # "NAT (nitric acid trihydrate)" # "NAD (nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particle)" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 14. Radiation Characteristics of the atmosphere radiation process 14.1. Aerosols Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Aerosols whose radiative effect is taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15. Radiation --&gt; Shortwave Radiation Properties of the shortwave radiation scheme 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of shortwave radiation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 15.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_integration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "wide-band model" # "correlated-k" # "exponential sum fitting" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.3. Spectral Integration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Shortwave radiation scheme spectral integration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.transport_calculation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "two-stream" # "layer interaction" # "bulk" # "adaptive" # "multi-stream" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 15.4. Transport Calculation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Shortwave radiation transport calculation methods End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_intervals') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 15.5. Spectral Intervals Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Shortwave radiation scheme number of spectral intervals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.greenhouse_gas_complexity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CO2" # "CH4" # "N2O" # "CFC-11 eq" # "CFC-12 eq" # "HFC-134a eq" # "Explicit ODSs" # "Explicit other fluorinated gases" # "O3" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16. Radiation --&gt; Shortwave GHG Representation of greenhouse gases in the shortwave radiation scheme 16.1. Greenhouse Gas Complexity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Complexity of greenhouse gases whose shortwave radiative effects are taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.ODS') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CFC-12" # "CFC-11" # "CFC-113" # "CFC-114" # "CFC-115" # "HCFC-22" # "HCFC-141b" # "HCFC-142b" # "Halon-1211" # "Halon-1301" # "Halon-2402" # "methyl chloroform" # "carbon tetrachloride" # "methyl chloride" # "methylene chloride" # "chloroform" # "methyl bromide" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.2. ODS Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Ozone depleting substances whose shortwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.other_flourinated_gases') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HFC-134a" # "HFC-23" # "HFC-32" # "HFC-125" # "HFC-143a" # "HFC-152a" # "HFC-227ea" # "HFC-236fa" # "HFC-245fa" # "HFC-365mfc" # "HFC-43-10mee" # "CF4" # "C2F6" # "C3F8" # "C4F10" # "C5F12" # "C6F14" # "C7F16" # "C8F18" # "c-C4F8" # "NF3" # "SF6" # "SO2F2" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 16.3. Other Flourinated Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other flourinated gases whose shortwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17. Radiation --&gt; Shortwave Cloud Ice Shortwave radiative properties of ice crystals in clouds 17.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with cloud ice crystals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bi-modal size distribution" # "ensemble of ice crystals" # "mean projected area" # "ice water path" # "crystal asymmetry" # "crystal aspect ratio" # "effective crystal radius" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud ice crystals in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 17.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud ice crystals in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18. Radiation --&gt; Shortwave Cloud Liquid Shortwave radiative properties of liquid droplets in clouds 18.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with cloud liquid droplets End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud droplet number concentration" # "effective cloud droplet radii" # "droplet size distribution" # "liquid water path" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud liquid droplets in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "geometric optics" # "Mie theory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 18.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud liquid droplets in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_inhomogeneity.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Monte Carlo Independent Column Approximation" # "Triplecloud" # "analytic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 19. Radiation --&gt; Shortwave Cloud Inhomogeneity Cloud inhomogeneity in the shortwave radiation scheme 19.1. Cloud Inhomogeneity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for taking into account horizontal cloud inhomogeneity End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20. Radiation --&gt; Shortwave Aerosols Shortwave radiative properties of aerosols 20.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with aerosols End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "number concentration" # "effective radii" # "size distribution" # "asymmetry" # "aspect ratio" # "mixing state" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of aerosols in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 20.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to aerosols in the shortwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_gases.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 21. Radiation --&gt; Shortwave Gases Shortwave radiative properties of gases 21.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with gases End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22. Radiation --&gt; Longwave Radiation Properties of the longwave radiation scheme 22.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of longwave radiation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 22.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the longwave radiation scheme. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_integration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "wide-band model" # "correlated-k" # "exponential sum fitting" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22.3. Spectral Integration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Longwave radiation scheme spectral integration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.transport_calculation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "two-stream" # "layer interaction" # "bulk" # "adaptive" # "multi-stream" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 22.4. Transport Calculation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Longwave radiation transport calculation methods End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_intervals') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 22.5. Spectral Intervals Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Longwave radiation scheme number of spectral intervals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.greenhouse_gas_complexity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CO2" # "CH4" # "N2O" # "CFC-11 eq" # "CFC-12 eq" # "HFC-134a eq" # "Explicit ODSs" # "Explicit other fluorinated gases" # "O3" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23. Radiation --&gt; Longwave GHG Representation of greenhouse gases in the longwave radiation scheme 23.1. Greenhouse Gas Complexity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Complexity of greenhouse gases whose longwave radiative effects are taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.ODS') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CFC-12" # "CFC-11" # "CFC-113" # "CFC-114" # "CFC-115" # "HCFC-22" # "HCFC-141b" # "HCFC-142b" # "Halon-1211" # "Halon-1301" # "Halon-2402" # "methyl chloroform" # "carbon tetrachloride" # "methyl chloride" # "methylene chloride" # "chloroform" # "methyl bromide" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23.2. ODS Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Ozone depleting substances whose longwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.other_flourinated_gases') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HFC-134a" # "HFC-23" # "HFC-32" # "HFC-125" # "HFC-143a" # "HFC-152a" # "HFC-227ea" # "HFC-236fa" # "HFC-245fa" # "HFC-365mfc" # "HFC-43-10mee" # "CF4" # "C2F6" # "C3F8" # "C4F10" # "C5F12" # "C6F14" # "C7F16" # "C8F18" # "c-C4F8" # "NF3" # "SF6" # "SO2F2" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 23.3. Other Flourinated Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other flourinated gases whose longwave radiative effects are explicitly taken into account in the atmosphere model End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24. Radiation --&gt; Longwave Cloud Ice Longwave radiative properties of ice crystals in clouds 24.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with cloud ice crystals End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.physical_reprenstation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bi-modal size distribution" # "ensemble of ice crystals" # "mean projected area" # "ice water path" # "crystal asymmetry" # "crystal aspect ratio" # "effective crystal radius" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24.2. Physical Reprenstation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud ice crystals in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 24.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud ice crystals in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25. Radiation --&gt; Longwave Cloud Liquid Longwave radiative properties of liquid droplets in clouds 25.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with cloud liquid droplets End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud droplet number concentration" # "effective cloud droplet radii" # "droplet size distribution" # "liquid water path" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud liquid droplets in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "geometric optics" # "Mie theory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 25.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud liquid droplets in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_inhomogeneity.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Monte Carlo Independent Column Approximation" # "Triplecloud" # "analytic" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 26. Radiation --&gt; Longwave Cloud Inhomogeneity Cloud inhomogeneity in the longwave radiation scheme 26.1. Cloud Inhomogeneity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for taking into account horizontal cloud inhomogeneity End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27. Radiation --&gt; Longwave Aerosols Longwave radiative properties of aerosols 27.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with aerosols End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "number concentration" # "effective radii" # "size distribution" # "asymmetry" # "aspect ratio" # "mixing state" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of aerosols in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 27.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to aerosols in the longwave radiation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_gases.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 28. Radiation --&gt; Longwave Gases Longwave radiative properties of gases 28.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with gases End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 29. Turbulence Convection Atmosphere Convective Turbulence and Clouds 29.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of atmosphere convection and turbulence End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Mellor-Yamada" # "Holtslag-Boville" # "EDMF" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30. Turbulence Convection --&gt; Boundary Layer Turbulence Properties of the boundary layer turbulence scheme 30.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Boundary layer turbulence scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "TKE prognostic" # "TKE diagnostic" # "TKE coupled with water" # "vertical profile of Kz" # "non-local diffusion" # "Monin-Obukhov similarity" # "Coastal Buddy Scheme" # "Coupled with convection" # "Coupled with gravity waves" # "Depth capped at cloud base" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 30.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Boundary layer turbulence scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 30.3. Closure Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Boundary layer turbulence scheme closure order End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.counter_gradient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 30.4. Counter Gradient Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Uses boundary layer turbulence scheme counter gradient End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 31. Turbulence Convection --&gt; Deep Convection Properties of the deep convection scheme 31.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Deep convection scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mass-flux" # "adjustment" # "plume ensemble" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Deep convection scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CAPE" # "bulk" # "ensemble" # "CAPE/WFN based" # "TKE/CIN based" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.3. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Deep convection scheme method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vertical momentum transport" # "convective momentum transport" # "entrainment" # "detrainment" # "penetrative convection" # "updrafts" # "downdrafts" # "radiative effect of anvils" # "re-evaporation of convective precipitation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.4. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical processes taken into account in the parameterisation of deep convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.microphysics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "tuning parameter based" # "single moment" # "two moment" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 31.5. Microphysics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Microphysics scheme for deep convection. Microphysical processes directly control the amount of detrainment of cloud hydrometeor and water vapor from updrafts End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 32. Turbulence Convection --&gt; Shallow Convection Properties of the shallow convection scheme 32.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Shallow convection scheme name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mass-flux" # "cumulus-capped boundary layer" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N shallow convection scheme type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "same as deep (unified)" # "included in boundary layer turbulence" # "separate diagnosis" # TODO - please enter value(s) """ Explanation: 32.3. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 shallow convection scheme method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "convective momentum transport" # "entrainment" # "detrainment" # "penetrative convection" # "re-evaporation of convective precipitation" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.4. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical processes taken into account in the parameterisation of shallow convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.microphysics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "tuning parameter based" # "single moment" # "two moment" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 32.5. Microphysics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Microphysics scheme for shallow convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 33. Microphysics Precipitation Large Scale Cloud Microphysics and Precipitation 33.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of large scale cloud microphysics and precipitation End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 34. Microphysics Precipitation --&gt; Large Scale Precipitation Properties of the large scale precipitation scheme 34.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name of the large scale precipitation parameterisation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.hydrometeors') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "liquid rain" # "snow" # "hail" # "graupel" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 34.2. Hydrometeors Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Precipitating hydrometeors taken into account in the large scale precipitation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics Properties of the large scale cloud microphysics scheme 35.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name of the microphysics parameterisation scheme used for large scale clouds. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mixed phase" # "cloud droplets" # "cloud ice" # "ice nucleation" # "water vapour deposition" # "effect of raindrops" # "effect of snow" # "effect of graupel" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 35.2. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Large scale cloud microphysics processes End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 36. Cloud Scheme Characteristics of the cloud scheme 36.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of the atmosphere cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 36.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.atmos_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "atmosphere_radiation" # "atmosphere_microphysics_precipitation" # "atmosphere_turbulence_convection" # "atmosphere_gravity_waves" # "atmosphere_solar" # "atmosphere_volcano" # "atmosphere_cloud_simulator" # TODO - please enter value(s) """ Explanation: 36.3. Atmos Coupling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Atmosphere components that are linked to the cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.uses_separate_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 36.4. Uses Separate Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Different cloud schemes for the different types of clouds (convective, stratiform and boundary layer) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "entrainment" # "detrainment" # "bulk cloud" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 36.5. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Processes included in the cloud scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 36.6. Prognostic Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the cloud scheme a prognostic scheme? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.diagnostic_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 36.7. Diagnostic Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the cloud scheme a diagnostic scheme? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud amount" # "liquid" # "ice" # "rain" # "snow" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 36.8. Prognostic Variables Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List the prognostic variables used by the cloud scheme, if applicable. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_overlap_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "random" # "maximum" # "maximum-random" # "exponential" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 37. Cloud Scheme --&gt; Optical Cloud Properties Optical cloud properties 37.1. Cloud Overlap Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Method for taking into account overlapping of cloud layers End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 37.2. Cloud Inhomogeneity Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Method for taking into account cloud inhomogeneity End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # TODO - please enter value(s) """ Explanation: 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution Sub-grid scale water distribution 38.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 38.2. Function Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution function name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 38.3. Function Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution function type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.convection_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "coupled with deep" # "coupled with shallow" # "not coupled with convection" # TODO - please enter value(s) """ Explanation: 38.4. Convection Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Sub-grid scale water distribution coupling with convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # TODO - please enter value(s) """ Explanation: 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution Sub-grid scale ice distribution 39.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 39.2. Function Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution function name End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 39.3. Function Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution function type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.convection_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "coupled with deep" # "coupled with shallow" # "not coupled with convection" # TODO - please enter value(s) """ Explanation: 39.4. Convection Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Sub-grid scale ice distribution coupling with convection End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 40. Observation Simulation Characteristics of observation simulation 40.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of observation simulator characteristics End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_estimation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "no adjustment" # "IR brightness" # "visible optical depth" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 41. Observation Simulation --&gt; Isscp Attributes ISSCP Characteristics 41.1. Top Height Estimation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Cloud simulator ISSCP top height estimation methodUo End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "lowest altitude level" # "highest altitude level" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 41.2. Top Height Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator ISSCP top height direction End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.run_configuration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Inline" # "Offline" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 42. Observation Simulation --&gt; Cosp Attributes CFMIP Observational Simulator Package attributes 42.1. Run Configuration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP run configuration End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_grid_points') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 42.2. Number Of Grid Points Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of grid points End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_sub_columns') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 42.3. Number Of Sub Columns Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of sub-cloumns used to simulate sub-grid variability End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 42.4. Number Of Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of levels End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.frequency') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 43. Observation Simulation --&gt; Radar Inputs Characteristics of the cloud radar simulator 43.1. Frequency Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar frequency (Hz) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "surface" # "space borne" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 43.2. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.gas_absorption') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 43.3. Gas Absorption Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar uses gas absorption End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.effective_radius') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 43.4. Effective Radius Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar uses effective radius End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.ice_types') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "ice spheres" # "ice non-spherical" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 44. Observation Simulation --&gt; Lidar Inputs Characteristics of the cloud lidar simulator 44.1. Ice Types Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator lidar ice type End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.overlap') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "max" # "random" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 44.2. Overlap Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Cloud simulator lidar overlap End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 45. Gravity Waves Characteristics of the parameterised gravity waves in the atmosphere, whether from orography or other sources. 45.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of gravity wave parameterisation in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.sponge_layer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Rayleigh friction" # "Diffusive sponge layer" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 45.2. Sponge Layer Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sponge layer in the upper levels in order to avoid gravity wave reflection at the top. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "continuous spectrum" # "discrete spectrum" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 45.3. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background wave distribution End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.subgrid_scale_orography') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "effect on drag" # "effect on lifting" # "enhanced topography" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 45.4. Subgrid Scale Orography Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Subgrid scale orography effects taken into account. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 46. Gravity Waves --&gt; Orographic Gravity Waves Gravity waves generated due to the presence of orography 46.1. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the orographic gravity wave scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.source_mechanisms') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "linear mountain waves" # "hydraulic jump" # "envelope orography" # "low level flow blocking" # "statistical sub-grid scale variance" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.2. Source Mechanisms Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Orographic gravity wave source mechanisms End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.calculation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "non-linear calculation" # "more than two cardinal directions" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.3. Calculation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Orographic gravity wave calculation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.propagation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "linear theory" # "non-linear theory" # "includes boundary layer ducting" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.4. Propagation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Orographic gravity wave propogation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.dissipation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "total wave" # "single wave" # "spectral" # "linear" # "wave saturation vs Richardson number" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 46.5. Dissipation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Orographic gravity wave dissipation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 47. Gravity Waves --&gt; Non Orographic Gravity Waves Gravity waves generated by non-orographic processes. 47.1. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the non-orographic gravity wave scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.source_mechanisms') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "convection" # "precipitation" # "background spectrum" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 47.2. Source Mechanisms Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Non-orographic gravity wave source mechanisms End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.calculation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "spatially dependent" # "temporally dependent" # TODO - please enter value(s) """ Explanation: 47.3. Calculation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Non-orographic gravity wave calculation method End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.propagation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "linear theory" # "non-linear theory" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 47.4. Propagation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Non-orographic gravity wave propogation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.dissipation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "total wave" # "single wave" # "spectral" # "linear" # "wave saturation vs Richardson number" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 47.5. Dissipation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Non-orographic gravity wave dissipation scheme End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 48. Solar Top of atmosphere solar insolation characteristics 48.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of solar insolation of the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_pathways.pathways') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "SW radiation" # "precipitating energetic particles" # "cosmic rays" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 49. Solar --&gt; Solar Pathways Pathways for solar forcing of the atmosphere 49.1. Pathways Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Pathways for the solar forcing of the atmosphere model domain End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "transient" # TODO - please enter value(s) """ Explanation: 50. Solar --&gt; Solar Constant Solar constant and top of atmosphere insolation characteristics 50.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of the solar constant. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.fixed_value') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 50.2. Fixed Value Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If the solar constant is fixed, enter the value of the solar constant (W m-2). End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.transient_characteristics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 50.3. Transient Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 solar constant transient characteristics (W m-2) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "transient" # TODO - please enter value(s) """ Explanation: 51. Solar --&gt; Orbital Parameters Orbital parameters and top of atmosphere insolation characteristics 51.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of orbital parameters End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.fixed_reference_date') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) """ Explanation: 51.2. Fixed Reference Date Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Reference date for fixed orbital parameters (yyyy) End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.transient_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 51.3. Transient Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of transient orbital parameters End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.computation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Berger 1978" # "Laskar 2004" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 51.4. Computation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method used for computing orbital parameters. End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.insolation_ozone.solar_ozone_impact') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) """ Explanation: 52. Solar --&gt; Insolation Ozone Impact of solar insolation on stratospheric ozone 52.1. Solar Ozone Impact Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does top of atmosphere insolation impact on stratospheric ozone? End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.volcanos.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) """ Explanation: 53. Volcanos Characteristics of the implementation of volcanoes 53.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of the implementation of volcanic effects in the atmosphere End of explanation """ # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.volcanos.volcanoes_treatment.volcanoes_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "high frequency solar constant anomaly" # "stratospheric aerosols optical thickness" # "Other: [Please specify]" # TODO - please enter value(s) """ Explanation: 54. Volcanos --&gt; Volcanoes Treatment Treatment of volcanoes in the atmosphere 54.1. Volcanoes Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How volcanic effects are modeled in the atmosphere. End of explanation """
aleph314/K2
Data Mining/Recommender Systems/Recommender-Engine_exercise.ipynb
gpl-3.0
import numpy as np import pandas as pd df = pd.read_csv('./data/ml-100k/u.data', sep='\t', header=None) df.columns = ['userid', 'itemid', 'rating', 'timestamp'] df['timestamp'] = pd.to_datetime(df['timestamp'],unit='s') df.head() """ Explanation: Recommender Engine Perhaps the most famous example of a recommender engine in the Data Science world was the Netflix competition started in 2006, in which teams from all around the world competed to improve on Netflix's reccomendation algorithm. The final prize of $1,000,000 was awarded to a team which developed a solution which had about a 10% increase in accuracy over Netflix's. In fact, this competition resulted in the development of some new techniques which are still in use. For more reading on this topic, see Simon Funk's blog post In this exercise, you will build a collaborative-filter recommendatin engine using both a cosine similarity approach and SVD (singular value decomposition). Before proceding download the MovieLens dataset. Importing and Pre-processing the Data First familiarize yourself with the data you downloaded, and then import the u.data file and take a look at the first few rows. End of explanation """ len(df['userid'].unique()), len(df['itemid'].unique()) from sklearn.model_selection import train_test_split dftrain, dftest = train_test_split(df, test_size=0.2) len(dftrain['userid'].unique()), len(dftrain['itemid'].unique()) missing_items = set(df['itemid'].unique()) - set(dftrain['itemid'].unique()) items = [] for item in missing_items: items.append([1, item, 0, np.nan]) dftrain_filled = dftrain.append(pd.DataFrame(items, columns=dftrain.columns)).reset_index() len(dftrain_filled['userid'].unique()), len(dftrain_filled['itemid'].unique()) len(dftest['userid'].unique()), len(dftest['itemid'].unique()) missing_items = set(df['itemid'].unique()) - set(dftest['itemid'].unique()) items = [] for item in missing_items: items.append([1, item, 0, np.nan]) dftest_filled = dftest.append(pd.DataFrame(items, columns=dftest.columns)).reset_index() len(dftest_filled['userid'].unique()), len(dftest_filled['itemid'].unique()) # X = pd.pivot_table(df, values='rating', index='userid', columns='itemid').fillna(0) # X.head() Xtrain = pd.pivot_table(dftrain_filled, values='rating', index='userid', columns='itemid').fillna(0) Xtest = pd.pivot_table(dftest_filled, values='rating', index='userid', columns='itemid').fillna(0) Xtrain.head() print(Xtrain.shape) print(Xtest.shape) """ Explanation: Before building any recommendation engines, we'll have to get the data into a useful form. Do this by first splitting the data into testing and training sets, and then by constructing two new dataframes whose columns are each unique movie and rows are each unique user, filling in 0 for missing values. End of explanation """ # from sklearn.model_selection import train_test_split # Xtrain, Xtest = train_test_split(X, test_size=0.2) """ Explanation: Now split the data into a training and test set, using a ratio 80/20 for train/test. End of explanation """ class cos_engine(): def __init__(self, k, how='user'): self.k = k self.how = how def _cos_sim(self, x, y): num = np.sum(x * y) den = np.sum(x**2) * np.sum(y**2) return num / np.sqrt(den) def _user_based_filtering(self, user, X): sim = X.apply(lambda row: self._cos_sim(X.loc[user, :].values, row.values), axis=1) sim = sim.drop(user, axis=0) rec = sim.sort_values(ascending=False).head(self.k) return rec def _item_based_filtering(self, item, X): Xt = X.T sim = Xt.apply(lambda row: self._cos_sim(Xt.loc[item, :].values, row.values), axis=1) sim = sim.drop(item, axis=0) rec = sim.sort_values(ascending=False).head(self.k) return rec def fit(self, X): if self.how == 'user': Xfilled = [] for user in X.index.values: ubf = self._user_based_filtering(user, X) weighted_sum = np.sum(X.loc[ubf.index, :].values * ubf.values.reshape(-1, 1), axis=0) Xfilled.append(weighted_sum / np.sum(np.abs(ubf.values))) self.Xfilled = pd.DataFrame(np.array(Xfilled), index=X.index, columns=X.columns) elif self.how == 'item': Xtfilled = [] for item in X.columns.values: ibf = self._item_based_filtering(item, X) Xt = X.T weighted_sum = np.sum(Xt.loc[ibf.index, :].values * ibf.values.reshape(-1, 1), axis=0) Xtfilled.append(weighted_sum / np.sum(np.abs(ibf.values))) self.Xfilled = pd.DataFrame(np.array(Xtfilled).T, index=X.index, columns=X.columns) else: print('Use either "user" or "item" for the parameter "how".') def predict(self, user, X): try: ratings = self.Xfilled.loc[user, :] rated_items = X.loc[user, :] > 0 ratings = ratings[~rated_items] return ratings.sort_values(ascending=False) except AttributeError: print('You have to fit the recommender first!') def score(self, X): try: return np.sum(np.sum(np.abs(self.Xfilled - X.where(X > 0)))) / X.where(X > 0).count().sum() except AttributeError: print('You have to fit the recommender first!') rec_ub = cos_engine(k=7) rec_ub.fit(Xtrain) rec_ub.Xfilled.loc[100, 258] rec_ub.predict(100, Xtrain + Xtest).head(10) rec_ub.score(Xtest) rec_ib = cos_engine(k=7, how='item') rec_ib.fit(Xtrain) rec_ib.Xfilled.loc[100, 258] rec_ib.predict(100, Xtrain + Xtest).head(10) rec_ib.score(Xtest) # class cos_engine(): # def __init__(self, k, how='user'): # self.k = k # self.how = how # def _cos_sim(self, x, y): # num = np.sum(x * y) # den = np.sum(x**2) * np.sum(y**2) # return num / np.sqrt(den) # def _user_based_filtering(self, user, X): # sim = X.apply(lambda row: self._cos_sim(X.loc[user, :].values, row.values), axis=1) # sim = sim.drop(user, axis=0) # rec = sim.sort_values(ascending=False)#.head(self.k) # return rec # def _item_based_filtering(self, item, X): # Xt = X.T # sim = Xt.apply(lambda row: self._cos_sim(Xt.loc[item, :].values, row.values), axis=1) # sim = sim.drop(item, axis=0) # rec = sim.sort_values(ascending=False)#.head(self.k) # return rec # def fit(self, user, X): # if self.how == 'user': # ubf = self._user_based_filtering(user, X) # rec = {} # for item in X.columns.values: # temp = X.loc[ubf.index, item] # rec[item] = ubf.loc[temp > 0].head(self.k) # self.rec = rec # elif self.how == 'item': # rec = {} # for item in X.columns.values: # print('Fitting item ', item) # This is pretty slow... # ibf = self._item_based_filtering(item, X) # Xt = X.T # temp = Xt.loc[ibf.index, user] # rec[item] = ibf.loc[temp > 0].head(self.k) # self.rec = rec # else: # print('Use either "user" or "item" for the parameter "how".') # def _predict_one(self, user, item, X): # try: # if self.how == 'user': # idx = self.rec[item].index # if len(idx) == 0: # return X.loc[user, item] # weighted_sum = np.sum(X.loc[idx, item].values * self.rec[item].values, axis=0) # return weighted_sum / np.sum(self.rec[item].values, axis=0) # elif self.how == 'item': # Xt = X.T # idx = self.rec[item].index # if len(idx) == 0: # return X.loc[user, item] # weighted_sum = np.sum(Xt.loc[idx, user].values * self.rec[item].values, axis=0) # return weighted_sum / np.sum(self.rec[item].values, axis=0) # except AttributeError: # print('You have to fit the recommender first!') # def predict(self, user, X): # pred = [] # for item in X.columns.values: # pred.append(self._predict_one(user, item, X)) # return pd.Series(np.array(np.round(pred), dtype=int), index=X.columns) # def score(self, user, X): # try: # pred = self.predict(user, X) # rated_items = X.loc[user, :] > 0 # user_ratings = X.loc[user, rated_items] # pred_ratings = pred.loc[rated_items] # return np.sum(user_ratings == pred_ratings) / len(user_ratings) # except AttributeError: # print('You have to fit the recommender first!') # solution # Libraries from sklearn.metrics.pairwise import cosine_similarity np.abs(cosine_similarity(Xtrain)).sum(axis=1).reshape(943, 1).shape """ Explanation: Cosine Similarity Building a recommendation engine can be thought of as "filling in the holes" in the sparse matrix you made above. For example, take a look at the MovieLense data. You'll see that that matrix is mostly zeros. Our task here is to predict what a given user will rate a given movie depending on the users tastes. To determine a users taste, we can use cosine similarity which is given by $$s_u^{cos}(u_k,u_a) = \frac{ u_k \cdot u_a }{ \left \| u_k \right \| \left \| u_a \right \| } = \frac{ \sum x_{k,m}x_{a,m} }{ \sqrt{\sum x_{k,m}^2\sum x_{a,m}^2} }$$ for users $u_a$ and $u_k$ on ratings given by $x_{a,m}$ and $x_{b,m}$. This is just the cosine of the angle between the two vectors. Likewise, this can also be calculated for the similarity between two items, $i_a$ and $i_b$, given by $$s_u^{cos}(i_m,i_b) = \frac{ i_m \cdot i_b }{ \left \| i_m \right \| \left \| i_b \right \| } = \frac{ \sum x_{a,m} x_{a,b} }{ \sqrt{ \sum x_{a,m}^2 \sum x_{a,b}^2 } }$$ Then, the similarity between two users is given by $$\hat{x}{k,m} = \bar{x}{k} + \frac{\sum\limits_{u_a} s_u^{cos}(u_k,u_a) (x_{a,m})}{\sum\limits_{u_a}|s_u^{cos}(u_k,u_a)|}$$ and for items given by $$\hat{x}{k,m} = \frac{\sum\limits{i_b} s_u^{cos}(i_m,i_b) (x_{k,b}) }{\sum\limits_{i_b}|s_u^{cos}(i_m,i_b)|}$$ Use these ideas to construct a class cos_engine which can be used to recommend movies for a given user. Be sure to also test your algorithm, reporting its accuracy. Bonus: Use adjusted cosine similiarity. End of explanation """ class svd_engine(): def __init__(self, k): self.k = k def fit(self, X): if self.k <= np.min(X.shape): U, S, V = np.linalg.svd(X) Uk = np.dot(U[:,:self.k], np.sqrt(np.diag(S[:self.k]))) Vk = np.dot(np.sqrt(np.diag(S[:self.k])), V[:self.k,:]) self.Xfilled = pd.DataFrame(np.dot(Uk, Vk), index=X.index, columns=X.columns) else: print('k has to be smaller than the minimum dimension of X') def predict(self, user, X): try: ratings = self.Xfilled.loc[user, :] rated_items = X.loc[user, :] > 0 ratings = ratings[~rated_items] return ratings.sort_values(ascending=False) except AttributeError: print('You have to fit the recommender first!') def score(self, X): try: return np.sum(np.sum(np.abs(self.Xfilled - X.where(X > 0)))) / X.where(X > 0).count().sum() except AttributeError: print('You have to fit the recommender first!') rec_svd = svd_engine(k=100) rec_svd.fit(Xtrain) rec_svd.Xfilled.loc[100, 258] rec_svd.predict(100, Xtrain + Xtest).head(10) rec_svd.score(Xtest) scores = [] for k in np.arange(10, 950, 10): rec_svd = svd_engine(k=k) rec_svd.fit(Xtrain) scores.append([k, rec_svd.score(Xtest)]) pd.DataFrame(scores, columns=['k', 'MAE']).sort_values(by='MAE').head() scores = [] for k in np.arange(2, 11): rec_svd = svd_engine(k=k) rec_svd.fit(Xtrain) scores.append([k, rec_svd.score(Xtest)]) pd.DataFrame(scores, columns=['k', 'MAE']).sort_values(by='MAE') rec_svd = svd_engine(k=10) rec_svd.fit(Xtrain) rec_svd.Xfilled.loc[100, 258] rec_svd.predict(100, Xtrain + Xtest).head(10) rec_svd.score(Xtest) """ Explanation: SVD Above we used Cosine Similarity to fill the holes in our sparse matrix. Another, and much more popular, method for matrix completion is called a Singluar Value Decomposition. SVD factors our data matrix into three smaller matricies, given by $$\textbf{M} = \textbf{U} \bf{\Sigma} \textbf{V}^*$$ where $\textbf{M}$ is our data matrix, $\textbf{U}$ is a unitary matrix containg the latent variables in the user space, $\bf{\Sigma}$ is diagonal matrix containing the singular values of $\textbf{M}$, and $\textbf{V}$ is a unitary matrix containing the latent variables in the item space. For more information on the SVD see the Wikipedia article. Numpy contains a package to estimate the SVD of a sparse matrix. By making estimates of the matricies $\textbf{U}$, $\bf{\Sigma}$, and $\textbf{V}$, and then by multiplying them together, we can reconstruct an estimate for the matrix $\textbf{M}$ with all the holes filled in. Use these ideas to construct a class svd_engine which can be used to recommend movies for a given user. Be sure to also test your algorithm, reporting its accuracy. Bonus: Tune any parameters. End of explanation """
cosmolejo/Fisica-Experimental-3
Constante_de_Planck/Constante_Plank.ipynb
gpl-3.0
import numpy as np #import pyfirmata as pyF from time import sleep import os import matplotlib.pyplot as plt %matplotlib inline from scipy import stats from scipy import constants as cons ###################################### ##VECTORES ###################################### led=[1.6325,2.424,2.566,3.7095] #ir,rojo,naranja,azul.... voltajes de activacion lamb=[1.10e6,1.60514e6,1.70648e6,2.14133e6] #para el ejercio inicial lamb_ajuste=[1.10e6,1.60514e6,1.70648e6,1.763668e6] #1/lambda #ir,rojo,naranja,azul lamb_ajuste2=[1.60514e6,1.70648e6,1.763668e6] IR=np.loadtxt("datos_IR.dat") Red=np.loadtxt("datos_rojo.dat") #Blue=np.loadtxt("datos_azul.dat") Green=np.loadtxt("datos_verde.dat") Orange=np.loadtxt("datos_naranja.dat") volt_IR=IR[:,0] volt_IR*=(3.3/5.) volt_red=Red[:,0] volt_red*=(3.3/5.) #volt_blue=Blue[:,0] volt_green=Green[:,0] volt_green*=(3.3/5.) volt_orange=Orange[:,0] volt_orange*=(3.3/5.) curr_IR=IR[:,1] curr_IR*=(3.3/5.) curr_red=Red[:,1] curr_red*=(3.3/5.) #curr_blue=Blue[:,1] curr_green=Green[:,1] curr_green*=(3.3/5.) curr_orange=Orange[:,1] curr_orange*=(3.3/5.) Vred=[] Ired=[] for i in range(len(curr_red)): if (volt_red[i]>1.716): if (volt_red[i]<=3.28053): Vred.append(volt_red[i]) Ired.append(curr_red[i]) #print (volt_red[i],curr_red[i]) Vgreen=[] Igreen=[] for i in range(len(curr_green)): #print (volt_green[i],curr_green[i]) if (volt_green[i]>2.39019): if (volt_green[i]<=3.19671): Vgreen.append(volt_green[i]) Igreen.append(curr_green[i]) #print (volt_green[i],curr_green[i]) Vorange=[] Iorange=[] for i in range(len(curr_orange)): #print (volt_orange[i],curr_orange[i]) if (volt_orange[i]>2.): if (volt_orange[i]<=3.19671): Vorange.append(volt_orange[i]) Iorange.append(curr_orange[i]) #print (volt_orange[i],curr_orange[i]) VIR=[] IIR=[] for i in range(len(curr_IR)): #print (volt_IR[i],curr_IR[i]) if (volt_IR[i]>1.5): if (volt_IR[i]<=3.): VIR.append(volt_IR[i]) IIR.append(curr_IR[i]) #print (volt_IR[i],curr_IR[i]) """ Explanation: Calculo de la Constante de Planck por: Yennifer Angarita Aarenas Alejandro Mesa Gómez para este experimento se sigue la guía propuesta en el articulo "Classroom fundamentals: measuring the Planck constant" de Maria Rute de Amorim e Sá Ferreira André y Paulo Sérgio de Brito André. en el cual se halla el voltaje de activación de diferentes leds y a partir de estos, su energía y finalmente a plicando la ecuacion: $$E_{p} = \frac{hc}{\lambda} $$ se puede despejar el valor de h Preparación del programa: End of explanation """ plt.plot(volt_IR,curr_IR,'ko') plt.plot(volt_red,curr_red,'ro') plt.plot(volt_orange,curr_orange,'yo') plt.plot(volt_green,curr_green,'go') """ Explanation: los ciclos for vistos antes se debieron usar, ya que los datos no tenían un comportamiento lineal como se mostrará a continuacion, por lo tanto, fue necesario hallar una zona donde existiese un comportamiento lineal, que siguiera el comportamiento planteado en el articulo. End of explanation """ led=np.array(led) led*=(3.3/5.) #lamb=[1.10e6,1.60514e6,1.70648e6,1.76367e6,2.14133e6] slope, intercept, r_value, p_value, std_err = stats.linregress(lamb,led) x=np.linspace(lamb[0],lamb[-1],100) y=slope*x+intercept plt.plot(lamb,led,'o') plt.plot(x,y,'-') plt.show() h_planck=slope*cons.e/cons.c h=cons.h error=(h_planck-h)/h print ('r: ',r_value) print ('pendiente: ',slope) print ('error: ',std_err) print ('h_planck: ',h_planck) print ('h_real: ',h) print ('error_h: ',error*100,'%') """ Explanation: el motivo de este comportamiento se debe a la forma en que se toman los datos, ya que variar la resistencia en los potenciometros azules usados en clase no era facil, si embargo, se realizó desde un valor de voltaje lo suficientemente bajo para que no pasara corriente por el led, hasta los 3.3 voltios que ofrece la tarjeta Chipkit. Primera Aproximación Inicialmente para hallar los valores de voltaje de activacion tomamos un camino más empirico, variamos el voltaje hasta notar una pequeña chispa en el led y tomamos este valor de voltaje. Este procedimiento se realizó para un led infrarojo (el cual se miró a travez de una camara de celular para poder distinguir la emisión de luz), uno rojo, uno naranja y uno azul. Sus respectivos voltajes de activacion fueron graficados contra $1/\lambda$ provisto por el articulo y finalmente se ajustó usando las funciones de scipy obteniendose lo siguiente: End of explanation """ plt.plot(VIR,IIR,'ro') pendiente, intercepto, r_value, p_value, std_err = stats.linregress(VIR,IIR) yir=[] VActivacion_IR=intercepto*330 for i in VIR: yir.append((pendiente*i)+intercepto) plt.plot(VIR,yir,'k-') print ('medido ',led[0],'ajustado ',VActivacion_IR) print ('r: ',r_value) plt.plot(Vred,Ired,'ro') pendiente, intercepto, r_value, p_value, std_err = stats.linregress(Vred,Ired) yred=[] VActivacion_rojo=intercepto*330 for i in Vred: yred.append((pendiente*i)+intercepto) plt.plot(Vred,yred,'r-') print ('medido ',led[1],'ajustado ',VActivacion_rojo) print ('r: ',r_value) plt.plot(Vorange,Iorange,'yo') pendiente, intercepto, r_value, p_value, std_err = stats.linregress(Vorange,Iorange) yorange=[] VActivacion_naranja=intercepto*330 for i in Vorange: yorange.append((pendiente*i)+intercepto) plt.plot(Vorange,yorange,'k-') print ('medido ',led[-2],'ajustado',VActivacion_naranja) print ('r: ',r_value) plt.plot(Vgreen,Igreen,'go') pendiente, intercepto, r_value, p_value, std_err = stats.linregress(Vgreen,Igreen) ygreen=[] VActivacion_verde=intercepto*330 for i in Vgreen: ygreen.append((pendiente*i)+intercepto) plt.plot(Vgreen,ygreen,'k-') print ('ajustado',VActivacion_verde) print ('r: ',r_value) """ Explanation: aquí se puede ver que apezar de lo simple de este acercamiento, se obtuvo un error de tan solo $5 %$ respecto al valor real de $h$ extraido de la librería scipy. Segunda Aproximación en este intento se sigue el algoritmo prouesto por el articulo, graficar los voltajes contra las corrientes de los leds, luego, extraer su incercepto con el eje y como la corriente de activación y con la ley de ohm, el voltaje. en este caso se usaron leds de color: infrarojo, rojo,naranja y verde, se deseaba usar un azul tambien pero los datos quedaron corruptos y no pudieron recuperarse End of explanation """ V_ajuste=[VActivacion_IR,VActivacion_rojo,VActivacion_naranja,VActivacion_verde] #ir,rojo,naranja,verde,azul #print (len(V_ajuste)) #print (len(lamb_ajuste)) slope, intercept, r_value, p_value, std_err = stats.linregress(lamb_ajuste,V_ajuste) x=np.linspace(lamb_ajuste[0],lamb_ajuste[-1],100) y=slope*x+intercept plt.plot(lamb_ajuste,V_ajuste,'o') plt.plot(x,y,'-') plt.show() h_planck=slope*cons.e/cons.c h=cons.h error=abs(h_planck-h)/h print ('r: ',r_value) print ('pendiente: ',slope) print ('error: ',std_err) print ('h_planck: ',h_planck) print ('h_real: ',h) print ('error_h: ',error*100, '%') """ Explanation: una vez se obtienen los datos, se procede arealizar el mismo ajuste de la primera aproximacion, pero con un error mayor: End of explanation """ V_ajuste2=[VActivacion_rojo,VActivacion_naranja,VActivacion_verde] #ir,rojo,naranja,verde,azul #print (len(V_ajuste2)) #print (len(lamb_ajuste2)) slope, intercept, r_value, p_value, std_err = stats.linregress(lamb_ajuste2,V_ajuste2) x=np.linspace(lamb_ajuste[0],lamb_ajuste[-1],100) y=slope*x+intercept plt.plot(lamb_ajuste2,V_ajuste2,'o') plt.plot(x,y,'-') plt.show() h_planck=slope*cons.e/cons.c h=cons.h error=abs(h_planck-h)/h print ('r: ',r_value) print ('pendiente: ',slope) print ('error: ',std_err) print ('h_planck: ',h_planck) print ('h_real: ',h) print ('error_h: ',error*100) """ Explanation: la explicación posible de este mayor error puede ser el hecho de que no se siguió un procedimiento riguroso y formarl para encontrar las corrientes con comportamiento lineal en cada caso. solo se buscó la zona con mejor linealidad. finalmente, se quizó estudiar el posible resultado al eliminar el led infrarojo, el cual como se observa en la grafica de su voltaje, no dió valores muy estables, además de tener una r de tan solo $0.5$ lo cual es bastante bajo en comparacion de los demás leds. End of explanation """
statsmodels/statsmodels.github.io
v0.13.1/examples/notebooks/generated/statespace_sarimax_internet.ipynb
bsd-3-clause
%matplotlib inline import numpy as np import pandas as pd from scipy.stats import norm import statsmodels.api as sm import matplotlib.pyplot as plt import requests from io import BytesIO from zipfile import ZipFile # Download the dataset dk = requests.get('http://www.ssfpack.com/files/DK-data.zip').content f = BytesIO(dk) zipped = ZipFile(f) df = pd.read_table( BytesIO(zipped.read('internet.dat')), skiprows=1, header=None, sep='\s+', engine='python', names=['internet','dinternet'] ) """ Explanation: SARIMAX: Model selection, missing data The example mirrors Durbin and Koopman (2012), Chapter 8.4 in application of Box-Jenkins methodology to fit ARMA models. The novel feature is the ability of the model to work on datasets with missing values. End of explanation """ # Get the basic series dta_full = df.dinternet[1:].values dta_miss = dta_full.copy() # Remove datapoints missing = np.r_[6,16,26,36,46,56,66,72,73,74,75,76,86,96]-1 dta_miss[missing] = np.nan """ Explanation: Model Selection As in Durbin and Koopman, we force a number of the values to be missing. End of explanation """ import warnings aic_full = pd.DataFrame(np.zeros((6,6), dtype=float)) aic_miss = pd.DataFrame(np.zeros((6,6), dtype=float)) warnings.simplefilter('ignore') # Iterate over all ARMA(p,q) models with p,q in [0,6] for p in range(6): for q in range(6): if p == 0 and q == 0: continue # Estimate the model with no missing datapoints mod = sm.tsa.statespace.SARIMAX(dta_full, order=(p,0,q), enforce_invertibility=False) try: res = mod.fit(disp=False) aic_full.iloc[p,q] = res.aic except: aic_full.iloc[p,q] = np.nan # Estimate the model with missing datapoints mod = sm.tsa.statespace.SARIMAX(dta_miss, order=(p,0,q), enforce_invertibility=False) try: res = mod.fit(disp=False) aic_miss.iloc[p,q] = res.aic except: aic_miss.iloc[p,q] = np.nan """ Explanation: Then we can consider model selection using the Akaike information criteria (AIC), but running the model for each variant and selecting the model with the lowest AIC value. There are a couple of things to note here: When running such a large batch of models, particularly when the autoregressive and moving average orders become large, there is the possibility of poor maximum likelihood convergence. Below we ignore the warnings since this example is illustrative. We use the option enforce_invertibility=False, which allows the moving average polynomial to be non-invertible, so that more of the models are estimable. Several of the models do not produce good results, and their AIC value is set to NaN. This is not surprising, as Durbin and Koopman note numerical problems with the high order models. End of explanation """ # Statespace mod = sm.tsa.statespace.SARIMAX(dta_miss, order=(1,0,1)) res = mod.fit(disp=False) print(res.summary()) # In-sample one-step-ahead predictions, and out-of-sample forecasts nforecast = 20 predict = res.get_prediction(end=mod.nobs + nforecast) idx = np.arange(len(predict.predicted_mean)) predict_ci = predict.conf_int(alpha=0.5) # Graph fig, ax = plt.subplots(figsize=(12,6)) ax.xaxis.grid() ax.plot(dta_miss, 'k.') # Plot ax.plot(idx[:-nforecast], predict.predicted_mean[:-nforecast], 'gray') ax.plot(idx[-nforecast:], predict.predicted_mean[-nforecast:], 'k--', linestyle='--', linewidth=2) ax.fill_between(idx, predict_ci[:, 0], predict_ci[:, 1], alpha=0.15) ax.set(title='Figure 8.9 - Internet series'); """ Explanation: For the models estimated over the full (non-missing) dataset, the AIC chooses ARMA(1,1) or ARMA(3,0). Durbin and Koopman suggest the ARMA(1,1) specification is better due to parsimony. $$ \text{Replication of:}\ \textbf{Table 8.1} ~~ \text{AIC for different ARMA models.}\ \newcommand{\r}[1]{{\color{red}{#1}}} \begin{array}{lrrrrrr} \hline q & 0 & 1 & 2 & 3 & 4 & 5 \ \hline p & {} & {} & {} & {} & {} & {} \ 0 & 0.00 & 549.81 & 519.87 & 520.27 & 519.38 & 518.86 \ 1 & 529.24 & \r{514.30} & 516.25 & 514.58 & 515.10 & 516.28 \ 2 & 522.18 & 516.29 & 517.16 & 515.77 & 513.24 & 514.73 \ 3 & \r{511.99} & 513.94 & 515.92 & 512.06 & 513.72 & 514.50 \ 4 & 513.93 & 512.89 & nan & nan & 514.81 & 516.08 \ 5 & 515.86 & 517.64 & nan & nan & nan & nan \ \hline \end{array} $$ For the models estimated over missing dataset, the AIC chooses ARMA(1,1) $$ \text{Replication of:}\ \textbf{Table 8.2} ~~ \text{AIC for different ARMA models with missing observations.}\ \begin{array}{lrrrrrr} \hline q & 0 & 1 & 2 & 3 & 4 & 5 \ \hline p & {} & {} & {} & {} & {} & {} \ 0 & 0.00 & 488.93 & 464.01 & 463.86 & 462.63 & 463.62 \ 1 & 468.01 & \r{457.54} & 459.35 & 458.66 & 459.15 & 461.01 \ 2 & 469.68 & nan & 460.48 & 459.43 & 459.23 & 460.47 \ 3 & 467.10 & 458.44 & 459.64 & 456.66 & 459.54 & 460.05 \ 4 & 469.00 & 459.52 & nan & 463.04 & 459.35 & 460.96 \ 5 & 471.32 & 461.26 & nan & nan & 461.00 & 462.97 \ \hline \end{array} $$ Note: the AIC values are calculated differently than in Durbin and Koopman, but show overall similar trends. Postestimation Using the ARMA(1,1) specification selected above, we perform in-sample prediction and out-of-sample forecasting. End of explanation """
geektoni/shogun
doc/ipython-notebooks/structure/FGM.ipynb
bsd-3-clause
%pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') import numpy as np import scipy.io dataset = scipy.io.loadmat(os.path.join(SHOGUN_DATA_DIR, 'ocr/ocr_taskar.mat')) # patterns for training p_tr = dataset['patterns_train'] # patterns for testing p_ts = dataset['patterns_test'] # labels for training l_tr = dataset['labels_train'] # labels for testing l_ts = dataset['labels_test'] # feature dimension n_dims = p_tr[0,0].shape[0] # number of states n_stats = 26 # number of training samples n_tr_samples = p_tr.shape[1] # number of testing samples n_ts_samples = p_ts.shape[1] """ Explanation: General Structured Output Models with Shogun Machine Learning Toolbox Shell Hu (GitHub ID: hushell) Thanks Patrick Pletscher and Fernando J. Iglesias García for taking time to help me finish the project! Shoguners = awesome! Me = grateful! Introduction This notebook illustrates the training of a <a href="http://en.wikipedia.org/wiki/Factor_graph">factor graph</a> model using <a href="http://en.wikipedia.org/wiki/Structured_support_vector_machine">structured SVM</a> in Shogun. We begin by giving a brief outline of factor graphs and <a href="http://en.wikipedia.org/wiki/Structured_prediction">structured output learning</a> followed by the corresponding API in Shogun. Finally, we test the scalability by performing an experiment on a real <a href="http://en.wikipedia.org/wiki/Optical_character_recognition">OCR</a> data set for <a href="http://en.wikipedia.org/wiki/Handwriting_recognition">handwritten character recognition</a>. Factor Graph A factor graph explicitly represents the factorization of an undirected graphical model in terms of a set of factors (potentials), each of which is defined on a clique in the original graph [1]. For example, a MRF distribution can be factorized as $$ P(\mathbf{y}) = \frac{1}{Z} \prod_{F \in \mathcal{F}} \theta_F(\mathbf{y}_F), $$ where $F$ is the factor index, $\theta_F(\mathbf{y}_F)$ is the energy with respect to assignment $\mathbf{y}_F$. In this demo, we focus only on table representation of factors. Namely, each factor holds an energy table $\theta_F$, which can be viewed as an unnormalized CPD. According to different factorizations, there are different types of factors. Usually we assume the Markovian property is held, that is, factors have the same parameterization if they belong to the same type, no matter how location or time changes. In addition, we have parameter free factor type, but nothing to learn for such kinds of types. More detailed implementation will be explained later. Structured Prediction Structured prediction typically involves an input $\mathbf{x}$ (can be structured) and a structured output $\mathbf{y}$. A joint feature map $\Phi(\mathbf{x},\mathbf{y})$ is defined to incorporate structure information into the labels, such as chains, trees or general graphs. In general, the linear parameterization will be used to give the prediction rule. We leave the kernelized version for future work. $$ \hat{\mathbf{y}} = \underset{\mathbf{y} \in \mathcal{Y}}{\operatorname{argmax}} \langle \mathbf{w}, \Phi(\mathbf{x},\mathbf{y}) \rangle $$ where $\Phi(\mathbf{x},\mathbf{y})$ is the feature vector by mapping local factor features to corresponding locations in terms of $\mathbf{y}$, and $\mathbf{w}$ is the global parameter vector. In factor graph model, parameters are associated with a set of factor types. So $\mathbf{w}$ is a collection of local parameters. The parameters are learned by regularized risk minimization, where the risk defined by user provided loss function $\Delta(\mathbf{y},\mathbf{\hat{y}})$ is usually non-convex and non-differentiable, e.g. the Hamming loss. So the empirical risk is defined in terms of the surrogate hinge loss $H_i(\mathbf{w}) = \max_{\mathbf{y} \in \mathcal{Y}} \Delta(\mathbf{y}_i,\mathbf{y}) - \langle \mathbf{w}, \Psi_i(\mathbf{y}) \rangle $, which is an upper bound of the user defined loss. Here $\Psi_i(\mathbf{y}) = \Phi(\mathbf{x}_i,\mathbf{y}_i) - \Phi(\mathbf{x}_i,\mathbf{y})$. The training objective is given by $$ \min_{\mathbf{w}} \frac{\lambda}{2} ||\mathbf{w}||^2 + \frac{1}{N} \sum_{i=1}^N H_i(\mathbf{w}). $$ In Shogun's factor graph model, the corresponding implemented functions are: <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1StructuredModel.html#a15bd99e15bbf0daa8a727d03dbbf4bcd">FactorGraphModel::get_joint_feature_vector()</a> $\longleftrightarrow \Phi(\mathbf{x}_i,\mathbf{y})$ <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1FactorGraphModel.html#a36665cfdd7ea2dfcc9b3c590947fe67f">FactorGraphModel::argmax()</a> $\longleftrightarrow H_i(\mathbf{w})$ <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1FactorGraphModel.html#a17dac99e933f447db92482a6dce8489b">FactorGraphModel::delta_loss()</a> $\longleftrightarrow \Delta(\mathbf{y}_i,\mathbf{y})$ Experiment: OCR Show Data First of all, we load the OCR data from a prepared mat file. The raw data can be downloaded from <a href="http://www.seas.upenn.edu/~taskar/ocr/">http://www.seas.upenn.edu/~taskar/ocr/</a>. It has 6876 handwritten words with an average length of 8 letters from 150 different persons. Each letter is rasterized into a binary image of size 16 by 8 pixels. Thus, each $\mathbf{y}$ is a chain, and each node has 26 possible states denoting ${a,\cdots,z}$. End of explanation """ import matplotlib.pyplot as plt def show_word(patterns, index): """show a word with padding""" plt.rc('image', cmap='binary') letters = patterns[0,index][:128,:] n_letters = letters.shape[1] for l in range(n_letters): lett = np.transpose(np.reshape(letters[:,l], (8,16))) lett = np.hstack((np.zeros((16,1)), lett, np.zeros((16,1)))) lett = np.vstack((np.zeros((1,10)), lett, np.zeros((1,10)))) subplot(1,n_letters,l+1) imshow(lett) plt.xticks(()) plt.yticks(()) plt.tight_layout() show_word(p_tr, 174) show_word(p_tr, 471) show_word(p_tr, 57) """ Explanation: Few examples of the handwritten words are shown below. Note that the first capitalized letter has been removed. End of explanation """ from shogun import TableFactorType # unary, type_id = 0 cards_u = np.array([n_stats], np.int32) w_gt_u = np.zeros(n_stats*n_dims) fac_type_u = TableFactorType(0, cards_u, w_gt_u) # pairwise, type_id = 1 cards = np.array([n_stats,n_stats], np.int32) w_gt = np.zeros(n_stats*n_stats) fac_type = TableFactorType(1, cards, w_gt) # first bias, type_id = 2 cards_s = np.array([n_stats], np.int32) w_gt_s = np.zeros(n_stats) fac_type_s = TableFactorType(2, cards_s, w_gt_s) # last bias, type_id = 3 cards_t = np.array([n_stats], np.int32) w_gt_t = np.zeros(n_stats) fac_type_t = TableFactorType(3, cards_t, w_gt_t) # all initial parameters w_all = [w_gt_u,w_gt,w_gt_s,w_gt_t] # all factor types ftype_all = [fac_type_u,fac_type,fac_type_s,fac_type_t] """ Explanation: Define Factor Types and Build Factor Graphs Let's define 4 factor types, such that a word will be able to be modeled as a chain graph. The unary factor type will be used to define unary potentials that capture the appearance likelihoods of each letter. In our case, each letter has $16 \times 8$ pixels, thus there are $(16 \times 8 + 1) \times 26$ parameters. Here the additional bits in the parameter vector are bias terms. One for each state. The pairwise factor type will be used to define pairwise potentials between each pair of letters. This type in fact gives the Potts potentials. There are $26 \times 26$ parameters. The bias factor type for the first letter is a compensation factor type, since the interaction is one-sided. So there are $26$ parameters to be learned. The bias factor type for the last letter, which has the same intuition as the last item. There are also $26$ parameters. Putting all parameters together, the global parameter vector $\mathbf{w}$ has length $4082$. End of explanation """ def prepare_data(x, y, ftype, num_samples): """prepare FactorGraphFeatures and FactorGraphLabels """ from shogun import Factor, TableFactorType, FactorGraph from shogun import FactorGraphObservation, FactorGraphLabels, FactorGraphFeatures samples = FactorGraphFeatures(num_samples) labels = FactorGraphLabels(num_samples) for i in range(num_samples): n_vars = x[0,i].shape[1] data = x[0,i].astype(np.float64) vc = np.array([n_stats]*n_vars, np.int32) fg = FactorGraph(vc) # add unary factors for v in range(n_vars): datau = data[:,v] vindu = np.array([v], np.int32) facu = Factor(ftype[0], vindu, datau) fg.add_factor(facu) # add pairwise factors for e in range(n_vars-1): datap = np.array([1.0]) vindp = np.array([e,e+1], np.int32) facp = Factor(ftype[1], vindp, datap) fg.add_factor(facp) # add bias factor to first letter datas = np.array([1.0]) vinds = np.array([0], np.int32) facs = Factor(ftype[2], vinds, datas) fg.add_factor(facs) # add bias factor to last letter datat = np.array([1.0]) vindt = np.array([n_vars-1], np.int32) fact = Factor(ftype[3], vindt, datat) fg.add_factor(fact) # add factor graph samples.add_sample(fg) # add corresponding label states_gt = y[0,i].astype(np.int32) states_gt = states_gt[0,:]; # mat to vector loss_weights = np.array([1.0/n_vars]*n_vars) fg_obs = FactorGraphObservation(states_gt, loss_weights) labels.add_label(fg_obs) return samples, labels # prepare training pairs (factor graph, node states) n_tr_samples = 350 # choose a subset of training data to avoid time out on buildbot samples, labels = prepare_data(p_tr, l_tr, ftype_all, n_tr_samples) """ Explanation: Next, we write a function to construct the factor graphs and prepare labels for training. For each factor graph instance, the structure is a chain but the number of nodes and edges depend on the number of letters, where unary factors will be added for each letter, pairwise factors will be added for each pair of neighboring letters. Besides, the first and last letter will get an additional bias factor respectively. End of explanation """ try: import networkx as nx # pip install networkx except ImportError: import pip pip.main(['install', '--user', 'networkx']) import networkx as nx import matplotlib.pyplot as plt # create a graph G = nx.Graph() node_pos = {} # add variable nodes, assuming there are 3 letters G.add_nodes_from(['v0','v1','v2']) for i in range(3): node_pos['v%d' % i] = (2*i,1) # add factor nodes G.add_nodes_from(['F0','F1','F2','F01','F12','Fs','Ft']) for i in range(3): node_pos['F%d' % i] = (2*i,1.006) for i in range(2): node_pos['F%d%d' % (i,i+1)] = (2*i+1,1) node_pos['Fs'] = (-1,1) node_pos['Ft'] = (5,1) # add edges to connect variable nodes and factor nodes G.add_edges_from([('v%d' % i,'F%d' % i) for i in range(3)]) G.add_edges_from([('v%d' % i,'F%d%d' % (i,i+1)) for i in range(2)]) G.add_edges_from([('v%d' % (i+1),'F%d%d' % (i,i+1)) for i in range(2)]) G.add_edges_from([('v0','Fs'),('v2','Ft')]) # draw graph fig, ax = plt.subplots(figsize=(6,2)) nx.draw_networkx_nodes(G,node_pos,nodelist=['v0','v1','v2'],node_color='white',node_size=700,ax=ax) nx.draw_networkx_nodes(G,node_pos,nodelist=['F0','F1','F2'],node_color='yellow',node_shape='s',node_size=300,ax=ax) nx.draw_networkx_nodes(G,node_pos,nodelist=['F01','F12'],node_color='blue',node_shape='s',node_size=300,ax=ax) nx.draw_networkx_nodes(G,node_pos,nodelist=['Fs'],node_color='green',node_shape='s',node_size=300,ax=ax) nx.draw_networkx_nodes(G,node_pos,nodelist=['Ft'],node_color='purple',node_shape='s',node_size=300,ax=ax) nx.draw_networkx_edges(G,node_pos,alpha=0.7) plt.axis('off') plt.tight_layout() """ Explanation: An example of graph structure is visualized as below, from which you may have a better sense how a factor graph being built. Note that different colors are used to represent different factor types. End of explanation """ from shogun import FactorGraphModel, TREE_MAX_PROD # create model and register factor types model = FactorGraphModel(samples, labels, TREE_MAX_PROD) model.add_factor_type(ftype_all[0]) model.add_factor_type(ftype_all[1]) model.add_factor_type(ftype_all[2]) model.add_factor_type(ftype_all[3]) """ Explanation: Training Now we can create the factor graph model and start training. We will use the tree max-product belief propagation to do MAP inference. End of explanation """ from shogun import DualLibQPBMSOSVM from shogun import BmrmStatistics import pickle import time # create bundle method SOSVM, there are few variants can be chosen # BMRM, Proximal Point BMRM, Proximal Point P-BMRM, NCBM # usually the default one i.e. BMRM is good enough # lambda is set to 1e-2 bmrm = DualLibQPBMSOSVM(model, labels, 0.01) bmrm.put('m_TolAbs', 20.0) bmrm.put('verbose', True) bmrm.set_store_train_info(True) # train t0 = time.time() bmrm.train() t1 = time.time() w_bmrm = bmrm.get_real_vector('m_w') print("BMRM took", t1 - t0, "seconds.") """ Explanation: In Shogun, we implemented several batch solvers and online solvers. Let's first try to train the model using a batch solver. We choose the dual bundle method solver (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CDualLibQPBMSOSVM.html">DualLibQPBMSOSVM</a>) [2], since in practice it is slightly faster than the primal n-slack cutting plane solver (<a a href="http://www.shogun-toolbox.org/doc/en/latest/PrimalMosekSOSVM_8h.html">PrimalMosekSOSVM</a>) [3]. However, it still will take a while until convergence. Briefly, in each iteration, a gradually tighter piece-wise linear lower bound of the objective function will be constructed by adding more cutting planes (most violated constraints), then the approximate QP will be solved. Finding a cutting plane involves calling the max oracle $H_i(\mathbf{w})$ and in average $N$ calls are required in an iteration. This is basically why the training is time consuming. End of explanation """ import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4)) primal_bmrm = bmrm.get_helper().get_real_vector('primal') dual_bmrm = bmrm.get_result().get_hist_Fd_vector() len_iter = min(primal_bmrm.size, dual_bmrm.size) primal_bmrm = primal_bmrm[1:len_iter] dual_bmrm = dual_bmrm[1:len_iter] # plot duality gaps xs = range(dual_bmrm.size) axes[0].plot(xs, (primal_bmrm-dual_bmrm), label='duality gap') axes[0].set_xlabel('iteration') axes[0].set_ylabel('duality gap') axes[0].legend(loc=1) axes[0].set_title('duality gaps'); axes[0].grid(True) # plot primal and dual values xs = range(dual_bmrm.size-1) axes[1].plot(xs, primal_bmrm[1:], label='primal') axes[1].plot(xs, dual_bmrm[1:], label='dual') axes[1].set_xlabel('iteration') axes[1].set_ylabel('objective') axes[1].legend(loc=1) axes[1].set_title('primal vs dual'); axes[1].grid(True) """ Explanation: Let's check the duality gap to see if the training has converged. We aim at minimizing the primal problem while maximizing the dual problem. By the weak duality theorem, the optimal value of the primal problem is always greater than or equal to dual problem. Thus, we could expect the duality gap will decrease during the time. A relative small and stable duality gap may indicate the convergence. In fact, the gap doesn't have to become zero, since we know it is not far away from the local minima. End of explanation """ # statistics bmrm_stats = bmrm.get_result() nCP = bmrm_stats.nCP nzA = bmrm_stats.nzA print('number of cutting planes: %d' % nCP) print('number of active cutting planes: %d' % nzA) """ Explanation: There are other statitics may also be helpful to check if the solution is good or not, such as the number of cutting planes, from which we may have a sense how tight the piece-wise lower bound is. In general, the number of cutting planes should be much less than the dimension of the parameter vector. End of explanation """ from shogun import StochasticSOSVM # the 3rd parameter is do_weighted_averaging, by turning this on, # a possibly faster convergence rate may be achieved. # the 4th parameter controls outputs of verbose training information sgd = StochasticSOSVM(model, labels, True, True) sgd.put('num_iter', 100) sgd.put('lambda', 0.01) # train t0 = time.time() sgd.train() t1 = time.time() w_sgd = sgd.get_real_vector('m_w') print("SGD took", t1 - t0, "seconds.") """ Explanation: In our case, we have 101 active cutting planes, which is much less than 4082, i.e. the number of parameters. We could expect a good model by looking at these statistics. Now come to the online solvers. Unlike the cutting plane algorithms re-optimizes over all the previously added dual variables, an online solver will update the solution based on a single point. This difference results in a faster convergence rate, i.e. less oracle calls, please refer to Table 1 in [4] for more detail. Here, we use the stochastic subgradient descent (<a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CStochasticSOSVM.html">StochasticSOSVM</a>) to compare with the BMRM algorithm shown before. End of explanation """ fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4)) primal_sgd = sgd.get_helper().get_real_vector('primal') xs = range(dual_bmrm.size-1) axes[0].plot(xs, primal_bmrm[1:], label='BMRM') axes[0].plot(range(99), primal_sgd[1:100], label='SGD') axes[0].set_xlabel('effecitve passes') axes[0].set_ylabel('primal objective') axes[0].set_title('whole training progress') axes[0].legend(loc=1) axes[0].grid(True) axes[1].plot(range(99), primal_bmrm[1:100], label='BMRM') axes[1].plot(range(99), primal_sgd[1:100], label='SGD') axes[1].set_xlabel('effecitve passes') axes[1].set_ylabel('primal objective') axes[1].set_title('first 100 effective passes') axes[1].legend(loc=1) axes[1].grid(True) """ Explanation: We compare the SGD and BMRM in terms of the primal objectives versus effective passes. We first plot the training progress (until both algorithms converge) and then zoom in to check the first 100 passes. In order to make a fair comparison, we set the regularization constant to 1e-2 for both algorithms. End of explanation """ fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4)) terr_bmrm = bmrm.get_helper().get_real_vector('train_error') terr_sgd = sgd.get_helper().get_real_vector('train_error') xs = range(terr_bmrm.size-1) axes[0].plot(xs, terr_bmrm[1:], label='BMRM') axes[0].plot(range(99), terr_sgd[1:100], label='SGD') axes[0].set_xlabel('effecitve passes') axes[0].set_ylabel('training error') axes[0].set_title('whole training progress') axes[0].legend(loc=1) axes[0].grid(True) axes[1].plot(range(99), terr_bmrm[1:100], label='BMRM') axes[1].plot(range(99), terr_sgd[1:100], label='SGD') axes[1].set_xlabel('effecitve passes') axes[1].set_ylabel('training error') axes[1].set_title('first 100 effective passes') axes[1].legend(loc=1) axes[1].grid(True) """ Explanation: As is shown above, the SGD solver uses less oracle calls to get to converge. Note that the timing is 2 times slower than they actually need, since there are additional computations of primal objective and training error in each pass. The training errors of both algorithms for each pass are shown in below. End of explanation """ def hinton(matrix, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" ax = ax if ax is not None else plt.gca() if not max_weight: max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x,y),w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(w)) rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() # get pairwise parameters, also accessible from # w[n_dims*n_stats:n_dims*n_stats+n_stats*n_stats] model.w_to_fparams(w_sgd) # update factor parameters w_p = ftype_all[1].get_w() w_p = np.reshape(w_p,(n_stats,n_stats)) hinton(w_p) """ Explanation: Interestingly, the training errors of SGD solver are lower than BMRM's in first 100 passes, but in the end the BMRM solver obtains a better training performance. A probable explanation is that BMRM uses very limited number of cutting planes at beginning, which form a poor approximation of the objective function. As the number of cutting planes increasing, we got a tighter piecewise lower bound, thus improve the performance. In addition, we would like to show the pairwise weights, which may learn important co-occurrances of letters. The hinton diagram is a wonderful tool for visualizing 2D data, in which positive and negative values are represented by white and black squares, respectively, and the size of each square represents the magnitude of each value. In our case, a smaller number i.e. a large black square indicates the two letters tend to coincide. End of explanation """ # get testing data samples_ts, labels_ts = prepare_data(p_ts, l_ts, ftype_all, n_ts_samples) from shogun import FactorGraphFeatures, FactorGraphObservation, TREE_MAX_PROD, MAPInference # get a factor graph instance from test data fg0 = samples_ts.get_sample(100) fg0.compute_energies() fg0.connect_components() # create a MAP inference using tree max-product infer_met = MAPInference(fg0, TREE_MAX_PROD) infer_met.inference() # get inference results y_pred = infer_met.get_structured_outputs() y_truth = FactorGraphObservation.obtain_from_generic(labels_ts.get_label(100)) print(y_pred.get_data()) print(y_truth.get_data()) """ Explanation: Inference Next, we show how to do inference with the learned model parameters for a given data point. End of explanation """ from shogun import SOSVMHelper # training error of BMRM method bmrm.put('m_w', w_bmrm) model.w_to_fparams(w_bmrm) lbs_bmrm = bmrm.apply() acc_loss = 0.0 ave_loss = 0.0 for i in range(n_tr_samples): y_pred = lbs_bmrm.get_label(i) y_truth = labels.get_label(i) acc_loss = acc_loss + model.delta_loss(y_truth, y_pred) ave_loss = acc_loss / n_tr_samples print('BMRM: Average training error is %.4f' % ave_loss) # training error of stochastic method print('SGD: Average training error is %.4f' % SOSVMHelper.average_loss(w_sgd, model)) # testing error bmrm.set_features(samples_ts) bmrm.set_labels(labels_ts) lbs_bmrm_ts = bmrm.apply() acc_loss = 0.0 ave_loss_ts = 0.0 for i in range(n_ts_samples): y_pred = lbs_bmrm_ts.get_label(i) y_truth = labels_ts.get_label(i) acc_loss = acc_loss + model.delta_loss(y_truth, y_pred) ave_loss_ts = acc_loss / n_ts_samples print('BMRM: Average testing error is %.4f' % ave_loss_ts) # testing error of stochastic method print('SGD: Average testing error is %.4f' % SOSVMHelper.average_loss(sgd.get_real_vector('m_w'), model)) """ Explanation: Evaluation In the end, we check average training error and average testing error. The evaluation can be done by two methods. We can either use the apply() function in the structured output machine or use the <a href="http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CSOSVMHelper.html">SOSVMHelper</a>. End of explanation """
othersite/document
machinelearning/deep-learning-book/code/appendix_g_tensorflow-basics/appendix_g_tensorflow-basics.ipynb
apache-2.0
%load_ext watermark %watermark -a 'Sebastian Raschka' -d -p tensorflow,numpy """ Explanation: Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by Sebastian Raschka. All code examples are released under the MIT license. If you find this content useful, please consider supporting the work by buying a copy of the book. Other code examples and content are available on GitHub. The PDF and ebook versions of the book are available through Leanpub. Appendix G - TensorFlow Basics End of explanation """ import tensorflow as tf g = tf.Graph() with g.as_default() as g: tf_x = tf.constant([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) col_sum = tf.reduce_sum(tf_x, axis=0) print('tf_x:\n', tf_x) print('\ncol_sum:\n', col_sum) """ Explanation: Table of Contents TensorFlow in a Nutshell Installation Computation Graphs Variables Placeholder Variables Saving and Restoring Models Naming TensorFlow Objects CPU and GPU TensorBoard This appendix offers a brief overview of TensorFlow, an open-source library for numerical computation and deep learning. This section is intended for readers who want to gain a basic overview of this library before progressing through the hands-on sections that are concluding the main chapters. The majority of hands-on sections in this book focus on TensorFlow and its Python API, assuming that you have TensorFlow >=1.2 installed if you are planning to execute the code sections shown in this book. In addition to glancing over this appendix, I recommend the following resources from TensorFlow's official documentation for a more in-depth coverage on using TensorFlow: Download and setup instructions Python API documentation Tutorials TensorBoard, an optional tool for visualizing learning TensorFlow in a Nutshell At its core, TensorFlow is a library for efficient multidimensional array operations with a focus on deep learning. Developed by the Google Brain Team, TensorFlow was open-sourced on November 9th, 2015. And augmented by its convenient Python API layer, TensorFlow has gained much popularity and wide-spread adoption in industry as well as academia. TensorFlow shares some similarities with NumPy, such as providing data structures and computations based on multidimensional arrays. What makes TensorFlow particularly suitable for deep learning, though, are its primitives for defining functions on tensors, the ability of parallelizing tensor operations, and convenience tools such as automatic differentiation. While TensorFlow can be run entirely on a CPU or multiple CPUs, one of the core strength of this library is its support of GPUs (Graphical Processing Units) that are very efficient at performing highly parallelized numerical computations. In addition, TensorFlow also supports distributed systems as well as mobile computing platforms, including Android and Apple's iOS. But what is a tensor? In simplifying terms, we can think of tensors as multidimensional arrays of numbers, as a generalization of scalars, vectors, and matrices. Scalar: $\mathbb{R}$ Vector: $\mathbb{R}^n$ Matrix: $\mathbb{R}^n \times \mathbb{R}^m$ 3-Tensor: $\mathbb{R}^n \times \mathbb{R}^m \times \mathbb{R}^p$ ... When we describe tensors, we refer to its "dimensions" as the rank (or order) of a tensor, which is not to be confused with the dimensions of a matrix. For instance, an $m \times n$ matrix, where $m$ is the number of rows and $n$ is the number of columns, would be a special case of a rank-2 tensor. A visual explanation of tensors and their ranks is given is the figure below. Installation Code conventions in this book follow the Python 3.x syntax, and while the code examples should be backward compatible to Python 2.7, I highly recommend the use of Python >=3.5. Once you have your Python Environment set up ([Appendix - Python Setup]), the most convenient ways for installing TensorFlow are via pip or conda -- the latter only applies if you have the Anaconda/Miniconda Python distribution installed, which I prefer and recommend. Since TensorFlow is under active development, I recommend you to consult the official "Download and Setup" documentation for detailed installation instructions to install TensorFlow on you operating system, macOS, Linux, or Windows. Computation Graphs In contrast to other tools such as NumPy, the numerical computations in TensorFlow can be categorized into two steps: a construction step and an execution step. Consequently, the typical workflow in TensorFlow can be summarized as follows: Build a computational graph Start a new session to evaluate the graph Initialize variables Execute the operations in the compiled graph Note that the computation graph has no numerical values before we initialize and evaluate it. To see how this looks like in practice, let us set up a new graph for computing the column sums of a matrix, which we define as a constant tensor (reduce_sum is the TensorFlow equivalent of NumPy's sum function). End of explanation """ with tf.Session(graph=g) as sess: mat, csum = sess.run([tf_x, col_sum]) print('mat:\n', mat) print('\ncsum:\n', csum) """ Explanation: As we can see from the output above, the operations in the graph are represented as Tensor objects that require an explicit evaluation before the tf_x matrix is populated with numerical values and its column sum gets computed. Now, we pass the graph that we created earlier to a new, active session, where the graph gets compiled and evaluated: End of explanation """ g = tf.Graph() with g.as_default() as g: tf_x = tf.constant([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) col_sum = tf.reduce_sum(tf_x, axis=0) col_sum_times_2 = col_sum * 2 with tf.Session(graph=g) as sess: csum_2 = sess.run(col_sum_times_2) print('csum_2:\n', csum_2) """ Explanation: Note that if we are only interested in the result of a particular operation, we don't need to run its dependencies -- TensorFlow will automatically take care of that. For instance, we can directly fetch the numerical values of col_sum_times_2 in the active session without explicitly passing col_sum to sess.run(...) as the following example illustrates: End of explanation """ import tensorflow as tf g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) # add a constant to the matrix: tf_x = tf_x + x with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(tf_x) print(result) """ Explanation: Variables Variables are constructs in TensorFlow that allows us to store and update parameters of our models in the current session during training. To define a "variable" tensor, we use TensorFlow's Variable() constructor, which looks similar to the use of constant that we used to create a matrix previously. However, to execute a computational graph that contains variables, we must initialize all variables in the active session first (using tf.global_variables_initializer()), as illustrated in the example below. End of explanation """ with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(tf_x) result = sess.run(tf_x) print(result) """ Explanation: Now, let us do an experiment and evaluate the same graph twice: End of explanation """ g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(update_tf_x) result = sess.run(update_tf_x) print(result) """ Explanation: As we can see, the result of running the computation twice did not affect the numerical values fetched from the graph. To update or to assign new values to a variable, we use TensorFlow's assign operation. The function syntax of assign is assign(ref, val, ...), where 'ref' is updated by assigning 'value' to it: End of explanation """ import tensorflow as tf import numpy as np g = tf.Graph() with g.as_default() as g: tf_x = tf.placeholder(dtype=tf.float32, shape=(3, 2)) output = tf.matmul(tf_x, tf.transpose(tf_x)) with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) np_ary = np.array([[3., 4.], [5., 6.], [7., 8.]]) feed_dict = {tf_x: np_ary} print(sess.run(output, feed_dict=feed_dict)) """ Explanation: As we can see, the contents of the variable tf_x were successfully updated twice now; in the active session we initialized the variable tf_x added a constant scalar 1. to tf_x matrix via assign added a constant scalar 1. to the previously updated tf_x matrix via assign Although the example above is kept simple for illustrative purposes, variables are an important concept in TensorFlow, and we will see throughout the chapters, they are not only useful for updating model parameters but also for saving and loading variables for reuse. Placeholder Variables Another important concept in TensorFlow is the use of placeholder variables, which allow us to feed the computational graph with numerical values in an active session at runtime. In the following example, we will define a computational graph that performs a simple matrix multiplication operation. First, we define a placeholder variable that can hold 3x2-dimensional matrices. And after initializing the placeholder variable in the active session, we will use a dictionary, feed_dict we feed a NumPy array to the graph, which then evaluates the matrix multiplication operation. End of explanation """ import tensorflow as tf g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) # initialize a Saver, which gets all variables # within this computation graph context saver = tf.train.Saver() """ Explanation: Throughout the main chapters, we will make heavy use of placeholder variables, which allow us to pass our datasets to various learning algorithms in the computational graphs. Saving and Loading Variables Training deep neural networks requires a lot of computations and computational resources, and in practice, it would be infeasible to retrain our model each time we start a new TensorFlow session before we can use it to make predictions. In this section, we will go over the basics of saving and re-using the results of our TensorFlow models. The most convenient way to store the main components of our model is to use TensorFlows Saver class (tf.train.Saver()). To see how it works, let us reuse the simple example from the Variables section, where we added a constant 1. to all elements in a 3x2 matrix: End of explanation """ with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(update_tf_x) saver.save(sess, save_path='./my-model.ckpt') """ Explanation: Now, after we initialized the graph above, let us execute its operations in a new session: End of explanation """ g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) # initialize a Saver, which gets all variables # within this computation graph context saver = tf.train.Saver() with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) for epoch in range(100): result = sess.run(update_tf_x) if not epoch % 10: saver.save(sess, save_path='./my-model-multiple_ckpts.ckpt', global_step=epoch) """ Explanation: Notice the saver.save call above, which saves all variables in the graph to "checkpoint" files bearing the prefix my-model.ckpt in our local directory ('./'). Since we didn't specify which variables we wanted to save when we instantiated a tf.train.Saver(), it saved all variables in the graph by default -- here, we only have one variable, tf_x. Alternatively, if we are only interested in keeping particular variables, we can specify this by feeding tf.train.Saver() a dictionary or list of these variables upon instantiation. For example, if our graph contained more than one variable, but we were only interested in saving tf_x, we could instantiate a saver object as tf.train.Saver([tf_x]). After we executed the previous code example, we should find the three my-model.ckpt files (in binary format) in our local directory: my-model.ckpt.data-00000-of-00001 my-model.ckpt.index my-model.ckpt.meta The file my-model.ckpt.data-00000-of-00001 saves our main variable values, the .index file keeps track of the data structures, and the .meta file describes the structure of our computational graph that we executed. Note that in our simple example above, we just saved our variable one single time. However, in real-world applications, we typically train models over multiple iterations or epochs, and it is useful to create intermediate checkpoint files during training so that we can pick up where we left off in case we need to interrupt our session or encounter unforeseen technical difficulties. For instance, by using the global_step parameter, we could save our results after each 10th iteration by making the following modification to our code: End of explanation """ g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) # initialize a Saver, which gets all variables # within this computation graph context saver = tf.train.Saver() with tf.Session(graph=g) as sess: saver.restore(sess, save_path='./my-model.ckpt') result = sess.run(update_tf_x) print(result) """ Explanation: After we executed this code we find five my-model.ckpt files in our local directory: my-model.ckpt-50 {.data-00000-of-00001, .ckpt.index, .ckpt.meta} my-model.ckpt-60 {.data-00000-of-00001, .ckpt.index, .ckpt.meta} my-model.ckpt-70 {.data-00000-of-00001, .ckpt.index, .ckpt.meta} my-model.ckpt-80 {.data-00000-of-00001, .ckpt.index, .ckpt.meta} my-model.ckpt-90 {.data-00000-of-00001, .ckpt.index, .ckpt.meta} Although we saved our variables ten times, the saver only keeps the five most recent checkpoints by default to save storage space. However, if we want to keep more than five recent checkpoint files, we can provide an optional argument max_to_keep=n when we initialize the saver, where n is an integer specifying the number of the most recent checkpoint files we want to keep. Now that we learned how to save TensorFlow Variables, let us see how we can restore them. Assuming that we started a fresh computational session, we need to specify the graph first. Then, we can use the saver's restore method to restore our variables as shown below: End of explanation """ with tf.Session(graph=g) as sess: saver.restore(sess, save_path='./my-model-multiple_ckpts.ckpt-90') result = sess.run(update_tf_x) print(result) """ Explanation: Notice that the returned values of the tf_x Variable are now increased by a constant of two, compared to the values in the computational graph. The reason is that we ran the graph one time before we saved the variable, ```python with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(update_tf_x) # save the model saver.save(sess, save_path='./my-model.ckpt') ``` and we ran it a second time when after we restored the session. Similar to the example above, we can reload one of our checkpoint files by providing the desired checkpoint suffix (here: -90, which is the index of our last checkpoint): End of explanation """ import tensorflow as tf g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) tf_y = tf.Variable([[7., 8.], [9., 10.], [11., 12.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) saver = tf.train.Saver() with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(update_tf_x) saver.save(sess, save_path='./my-model.ckpt') """ Explanation: In this section, we merely covered the basics of saving and restoring TensorFlow models. If you want to learn more, please take a look at the official API documentation of TensorFlow's Saver class. Naming TensorFlow Objects When we create new TensorFlow objects like Variables, we can provide an optional argument for their name parameter -- for example: python tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], name='tf_x_0', dtype=tf.float32) Assigning names to Variables explicitly is not a requirement, but I personally recommend making it a habit when building (more) complex models. Let us walk through a scenario to illustrate the importance of naming variables, taking the simple example from the previous section and add new variable tf_y to the graph: End of explanation """ g = tf.Graph() with g.as_default() as g: tf_y = tf.Variable([[7., 8.], [9., 10.], [11., 12.]], dtype=tf.float32) tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) saver = tf.train.Saver() with tf.Session(graph=g) as sess: saver.restore(sess, save_path='./my-model.ckpt') result = sess.run(update_tf_x) print(result) """ Explanation: The variable tf_y does not do anything in the code example above; we added it for illustrative purposes, as we will see in a moment. Now, let us assume we started a new computational session and loaded our saved my-model into the following computational graph: End of explanation """ import tensorflow as tf g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], name='tf_x_0', dtype=tf.float32) tf_y = tf.Variable([[7., 8.], [9., 10., ]], name='tf_y_0', dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) saver = tf.train.Saver() with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) result = sess.run(update_tf_x) saver.save(sess, save_path='./my-model.ckpt') """ Explanation: Unless you paid close attention on how we initialized the graph above, this result above surely was not the one you expected. What happened? Intuitively, we expected our session to print python [[ 3. 4.] [ 5. 6.] [ 7. 8.]] The explanation behind this unexpected result is that we reversed the order of tf_y and tf_x in the graph above. TensorFlow applies a default naming scheme to all operations in the computational graph, unless we use do it explicitly via the name parameter -- or in other words, we confused TensorFlow by reversing the order of two similar objects, tf_y and tf_x. To circumvent this problem, we could give our variables specific names -- for example, 'tf_x_0' and 'tf_y_0': End of explanation """ g = tf.Graph() with g.as_default() as g: tf_y = tf.Variable([[7., 8.], [9., 10., ]], name='tf_y_0', dtype=tf.float32) tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], name='tf_x_0', dtype=tf.float32) x = tf.constant(1., dtype=tf.float32) update_tf_x = tf.assign(tf_x, tf_x + x) saver = tf.train.Saver() with tf.Session(graph=g) as sess: saver.restore(sess, save_path='./my-model.ckpt') result = sess.run(update_tf_x) print(result) """ Explanation: Then, even if we flip the order of these variables in a new computational graph, TensorFlow knows which values to use for each variable when loading our model -- assuming we provide the corresponding variable names: End of explanation """ import tensorflow as tf addition = True g = tf.Graph() with g.as_default() as g: x = tf.placeholder(dtype=tf.float32, shape=None) if addition: y = x + 1. else: y = x - 1. """ Explanation: CPU and GPU Please note that all code examples in this book, and all TensorFlow operations in general, can be executed on a CPU. If you have a GPU version of TensorFlow installed, TensorFlow will automatically execute those operations that have GPU support on GPUs and use your machine's CPU, otherwise. However, if you wish to define your computing device manually, for instance, if you have the GPU version installed but want to use the main CPU for prototyping, we can run an active section on a specific device using the with context as follows with tf.Session() as sess: with tf.device("/gpu:1"): where "/cpu:0": The CPU of your machine. "/gpu:0": The GPU of your machine, if you have one. "/gpu:1": The second GPU of your machine, etc. etc. You can get a list of all available devices on your machine via from tensorflow.python.client import device_lib device_lib.list_local_devices() For more information on using GPUs in TensorFlow, please refer to the GPU documentation at https://www.tensorflow.org/how_tos/using_gpu/. ```python with tf.Session() as sess: with tf.device("/gpu:1"): from tensorflow.python.client import device_lib device_lib.list_local_devices() ``` Another good way to check whether your current TensorFlow session runs on a GPU is to execute ```python import tensorflow as tf tf.test.gpu_device_name() `` In your current Python session. If a GPU is available to TensorFlow, it will return a non-empty string; for example,'/gpu:0'`. Otherwise, if now GPU can be found, the function will return an empty string. Control Flow It is important to discuss TensorFlow's control flow mechanics, the way it handles control statements such as if/else and while-loops. Control flow in TensorFlow is not a complicated topic, but it can be quite unintuitive at first and a common pitfall for beginners -- especially, in the context of how control flow in Python is handled. To explain control flow in TensorFlow in a practical manner, let us consider a simple example first. The following graph is meant to add the value 1.0 to a placeholder variable x if addition=True and subtract 1.0 from x otherwise: End of explanation """ with tf.Session(graph=g) as sess: result = sess.run(y, feed_dict={x: 1.}) print('Result:\n', result) """ Explanation: Now, let us create a new session and execute the graph by feeding a 1.0 to the placeholder. If everything works as expected, the session should return the value 2.0 since addition=True and 1.0 + 1.0 = 2.0: End of explanation """ addition = False with tf.Session(graph=g) as sess: result = sess.run(y, feed_dict={x: 1.}) print('Result:\n', result) """ Explanation: The previous session call clearly yielded the resulted we expected. Next, let us set addition=False to also check the other scenario, that is, subtracting 1.0 from x: End of explanation """ addition = True g = tf.Graph() with g.as_default() as g: addition = tf.placeholder(dtype=tf.bool, shape=None) x = tf.placeholder(dtype=tf.float32, shape=None) y = tf.cond(addition, true_fn=lambda: tf.add(x, 1.), false_fn=lambda: tf.subtract(x, 1.)) """ Explanation: It appears that the session did return the same value that it returned when addition was set to True. Why did this happen? The explanation for this is that the if/else statements in the previous code only apply to the graph construction step. Or in other words, we created a graph by visiting the code contained under the if statement, and since TensorFlow graphs are static, we have no way of running the code under the else statement -- except for setting addition=False and creating a new graph. However, we do not have to create a new graph each time we want to include control statements -- TensorFlow implements a variety of helper functions that help with control flow inside a graph. For instance, to accomplish the little exercise of conditionally adding or subtracting a one from the placeholder variable x, we could use tf.cond as follows: End of explanation """ with tf.Session(graph=g) as sess: result = sess.run(y, feed_dict={addition:True, x: 1.}) print('Result:\n', result) with tf.Session(graph=g) as sess: result = sess.run(y, feed_dict={addition:False, x: 1.}) print('Result:\n', result) """ Explanation: The basic use of tf.cond for conditional execution comes with three important arguments: a condition to check (here, if addition is True or False), a function that gets executed if the condition is True (true_fn) and a function that gets executed if the condition is False (false_fn), respectively. Next, let us repeat the little exercise from earlier and see if toggling the addition value between True and False affects the conditional execution that is now part of the graph: End of explanation """ import tensorflow as tf g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], name='tf_x_0', dtype=tf.float32) tf_y = tf.Variable([[7., 8.], [9., 10.], [11., 12.]], name='tf_y_0', dtype=tf.float32) output = tf_x + tf_y output = tf.matmul(tf.transpose(tf_x), output) """ Explanation: Finally, we get the expected results "1.0 + 1.0 = 2.0" if addition=True "1.0 - 1.0 = 0.0" if addition=False While this section provides you with the most important concept behind control flow in Python versus TensorFlow, there are many control statements (and logical operators) that we have not covered. Since the use of other control statements is analogous to tf.cond, I recommend you to visit TensorFlow's API documentation, which provides an overview of all the different operators for control flow and links to useful examples. TensorBoard TensorBoard is one of the coolest features of TensorFlow, which provides us with a suite of tools to visualize our computational graphs and operations before and during runtime. Especially, when we are implementing large neural networks, our graphs can be quite complicated, and TensorBoard is only useful to visually track the training cost and performance of our network, but it can also be used as an additional tool for debugging our implementation. In this section, we will go over the basic concepts of TensorBoard, but make sure you also check out the official documentation for more details. To visualize a computational graph via TensorBoard, let us create a simple graph with two Variables, the tensors tf_x and tf_y with shape [2, 3]. The first operation is to add these two tensors together. Second, we transpose tf_x and multiply it with tf_y: End of explanation """ with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) # create FileWrite object that writes the logs file_writer = tf.summary.FileWriter(logdir='logs/1', graph=g) result = sess.run(output) print(result) """ Explanation: If we want to visualize the graph via TensorBoard, we need to instantiate a new FileWriter object in our session, which we provide with a logdir and the graph itself. The FileWriter object will then write a protobuf file to the logdir path that we can load into TensorBoard: End of explanation """ # Graph visualization with name scopes g = tf.Graph() with g.as_default() as g: tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], name='tf_x_0', dtype=tf.float32) tf_y = tf.Variable([[7., 8.], [9., 10.], [11., 12.]], name='tf_y_0', dtype=tf.float32) # add custom name scope with tf.name_scope('addition'): output = tf_x + tf_y # add custom name scope with tf.name_scope('matrix_multiplication'): output = tf.matmul(tf.transpose(tf_x), output) with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) file_writer = tf.summary.FileWriter(logdir='logs/2', graph=g) result = sess.run(output) print(result) """ Explanation: If you installed TensorFlow via pip, the tensorboard command should be available from your command line terminal. So, after running the preceding code examples for defining the grap and running the session, you just need to execute the command tensorboard --logdir logs/1. You should then see an output similar to the following: Desktop Sebastian{$$} tensorboard --logdir logs/1 Starting TensorBoard b'41' on port 6006 (You can navigate to http://xxx.xxx.x.xx:6006) Copy and paste the http address from the terminal and open it in your favorite web browser to open the TensorBoard window. Then, click on the Graph tab at the top, to visualize the computational graph as shown in the figure below: In our TensorBoard window, we can now see a visual summary of our computational graph (as shown in the screenshot above). The dark-shaded nodes labeled as tf_x_0 and tf_y_0 are the two variables we initializes, and following the connective lines, we can track the flow of operations. We can see the graph edges that are connecting tf_x_0 and tf_y_0 to an add node, with is the addition we defined in the graph, followed by the multiplication with the transpose of and the result of add. Next, we are introducing the concept of name_scopes, which lets us organize different parts in our graph. In the following code example, we are going to take the initial code snippets and add with tf.name_scope(...) contexts as follows: End of explanation """ # Graph visualization and variable inspection g = tf.Graph() with g.as_default() as g: some_value = tf.placeholder(dtype=tf.int32, shape=None, name='some_value') tf_x = tf.Variable([[1., 2.], [3., 4.], [5., 6.]], name='tf_x_0', dtype=tf.float32) tf_y = tf.Variable([[7., 8.], [9., 10.], [11., 12.]], name='tf_y_0', dtype=tf.float32) with tf.name_scope('addition'): output = tf_x + tf_y with tf.name_scope('matrix_multiplication'): output = tf.matmul(tf.transpose(tf_x), output) with tf.name_scope('update_tensor_x'): tf_const = tf.constant(2., shape=None, name='some_const') update_tf_x = tf.assign(tf_x, tf_x * tf_const) # create summaries tf.summary.scalar(name='some_value', tensor=some_value) tf.summary.histogram(name='tf_x_values', values=tf_x) # merge all summaries into a single operation merged_summary = tf.summary.merge_all() """ Explanation: After executing the code example above, quit your previous TensorBoard session by pressing CTRL+C in the command line terminal and launch a new TensorBoard session via tensorboard --logdir logs/2. After you refreshed your browser window, you should see the following graph: Comparing this visualization to our initial one, we can see that our operations have been grouped into our custom name scopes. If we double-click on one of these name scope summary nodes, we can expand it and inspect the individual operations in more details as shown for the matrix_multiplication name scope in the screenshot below: So far, we have only been looking at the computational graph itself. However, TensorBoard implements many more useful features. In the following example, we will make use of the "Scalar" and "Histogram" tabs. The "Scalar" tab in TensorBoard allows us to track scalar values over time, and the "Histogram" tab is useful for displaying the distribution of value in our tensor Variables (for instance, the model parameters during training). For simplicity, let us take our previous code snippet and modify it to demonstrate the capabilities of TensorBoard: End of explanation """ with tf.Session(graph=g) as sess: sess.run(tf.global_variables_initializer()) # create FileWrite object that writes the logs file_writer = tf.summary.FileWriter(logdir='logs/3', graph=g) for i in range(5): # fetch the summary from the graph result, summary = sess.run([update_tf_x, merged_summary], feed_dict={some_value: i}) # write the summary to the log file_writer.add_summary(summary=summary, global_step=i) file_writer.flush() """ Explanation: Notice that we added an additional placeholder to the graph which later receives a scalar value from the session. We also added a new operation that updates our tf_x tensor by multiplying it with a constant 2.: python with tf.name_scope('update_tensor_x'): tf_const = tf.constant(2., shape=None, name='some_const') update_tf_x = tf.assign(tf_x, tf_x * tf_const) Finally, we added the lines ```python create summaries tf.summary.scalar(name='some_value', tensor=some_value) tf.summary.histogram(name='tf_x_values', values=tf_x) ``` at the end of our graph. These will create the "summaries" of the values we want to display in TensorBoard later. The last line of our graph is python merged_summary = tf.summary.merge_all() which summarizes all the tf.summary calls to one single operation, so that we only have to fetch one variable from the graph when we execute the session. When we executed the session, we simply fetched this merged summary from merged_summary as follows: python result, summary = sess.run([update_tf_x, merged_summary], feed_dict={some_value: i}) Next, let us add a for-loop to our session that runs the graph five times, and feeds the counter of the range iterator to the some_value placeholder variable: End of explanation """
GoogleCloudPlatform/vertex-ai-samples
notebooks/community/managed_notebooks/predictive_maintainance/predictive_maintenance_usecase.ipynb
apache-2.0
import os PROJECT_ID = "" # Get your Google Cloud project ID from gcloud if not os.getenv("IS_TESTING"): shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID: ", PROJECT_ID) """ Explanation: Predictive Maintenance Table of contents Overview Dataset Objective Costs Data analysis Fit a regression model Evaluate the trained model Save the model Running a notebook end-to-end using the executor Hosting the model on Vertex AI Create an endpoint Deploy the model to the created endpoint Test calling the endpoint Clean up Overview <a name="section-1"></a> This notebook demonstrates how to perform predictive maintenance on industrial data using machine learning techniques, deploy the machine learning model on Vertex AI, and automate the workflow using the executor feature of Vertex AI Workbench. Note: This notebook file was developed to run in a Vertex AI Workbench managed notebooks instance using the XGBoost (Local) kernel. Some components of this notebook may not work in other notebook environments. Dataset <a name="section-2"></a> The dataset used in this notebook is a part of the NASA Turbofan Engine Degradation Simulation dataset, which consists of simulated time-series data for four sets of fleet engines under different combinations of operational conditions and fault modes. In this notebook, only one of the engine's simulated data (FD001) has been used to analyze and train a model that can predict the engine's remaining useful life. Objectives <a name="section-3"></a> The objectives of this notebook include: Loading the required dataset from a Cloud Storage bucket. Analyzing the fields present in the dataset. Selecting the required data for the predictive maintenance model. Training an XGBoost regression model for predicting the remaining useful life. Evaluating the model. Running the notebook end-to-end as a training job using Executor. Deploying the model on Vertex AI. Clean up. Costs <a name="section-4"></a> This tutorial uses the following billable components of Google Cloud: Vertex AI Cloud Storage Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Before you begin Kernel selection Select <b>XGBoost</b> kernel while running this notebook on Vertex AI Workbench managed notebooks instances or ensure that the following libraries are installed in the environment where this notebook is being run. - XGBoost - Pandas - Seaborn - Sklearn Along with the above libraries, the following google-cloud libraries are also used in this notebook. google.cloud.aiplatform google.cloud.storage Set your project ID If you don't know your project ID, you may be able to get your project ID using gcloud. End of explanation """ if PROJECT_ID == "" or PROJECT_ID is None: PROJECT_ID = "[your-project-id]" # @param {type:"string"} """ Explanation: Otherwise, set your project ID here. End of explanation """ from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") """ Explanation: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial. End of explanation """ BUCKET_NAME = "[your-bucket-name]" BUCKET_URI = f"gs://{BUCKET_NAME}" REGION = "us-central1" # Set a default bucketname in case bucket name is not given if BUCKET_NAME == "" or BUCKET_NAME is None: from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP BUCKET_URI = "gs://" + BUCKET_NAME """ Explanation: Select or Create a Cloud Storage Bucket for storing the model When you create a model resource on Vertex AI using the Cloud SDK, you need to give a Cloud Storage bucket URI of the model where the model is stored. Using the model saved, you can then create Vertex AI model and endpoint resources in order to serve online predictions. Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets. You may also change the REGION variable, which is used for operations throughout the rest of this notebook. Make sure to choose a region where Vertex AI services are available. End of explanation """ ! gsutil mb -l $REGION $BUCKET_NAME """ Explanation: <b>Only if your bucket doesn't already exist</b>: Run the following cell to create your Cloud Storage bucket. End of explanation """ ! gsutil ls -al $BUCKET_NAME """ Explanation: Next, validate access to your Cloud Storage bucket by examining its contents: End of explanation """ import matplotlib.pyplot as plt import pandas as pd %matplotlib inline import os import numpy as np import seaborn as sns import xgboost as xgb from google.cloud import aiplatform, storage from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split """ Explanation: Import the required libraries End of explanation """ # load the data from the source INPUT_PATH = "gs://vertex_ai_managed_services_demo/mfg_predictive_maintenance/train_FD001.txt" # data source raw_data = pd.read_csv(INPUT_PATH, sep=" ", header=None) # check the data print(raw_data.shape) raw_data.head() """ Explanation: Load the data and check the data shape. End of explanation """ # name the columns (based on the original data source page) raw_data = raw_data[[f for f in range(0, 26)]] raw_data.columns = [ "ID", "Cycle", "OpSet1", "OpSet2", "OpSet3", "SensorMeasure1", "SensorMeasure2", "SensorMeasure3", "SensorMeasure4", "SensorMeasure5", "SensorMeasure6", "SensorMeasure7", "SensorMeasure8", "SensorMeasure9", "SensorMeasure10", "SensorMeasure11", "SensorMeasure12", "SensorMeasure13", "SensorMeasure14", "SensorMeasure15", "SensorMeasure16", "SensorMeasure17", "SensorMeasure18", "SensorMeasure19", "SensorMeasure20", "SensorMeasure21", ] raw_data.head() """ Explanation: The data itself doesn't contain any feature names and thus needs its columns to be renamed. The data source already provides some data description. Apparently, the <b>ID</b> column represents the unit-number of the fleet-engine and <b>Cycle</b> represents the time in cycles. <b>OpSet1</b>,<b>Opset2</b> & <b>Opset3</b> represent the three operational settings that are described in the original data source and have a substantial effect on engine performance. The rest of the fields show sensor readings collected from 21 different sensors. End of explanation """ # plot the cycle count for each IDs raw_data[["ID", "Cycle"]].groupby(by=["ID"]).count().plot(kind="bar", figsize=(12, 5)) """ Explanation: Data Analysis <a name="section-5"></a> The current dataset consists of timeseries data for various unit IDs. The data is represented in terms of cycles. Lets first see the distribution of number of cycles across the units. End of explanation """ # check the data-types raw_data.info() """ Explanation: On an average, there seem to be around 225 cycles per each ID in the dataset. Next, lets check the data types of the fields and the number of null records in the data. End of explanation """ # check the numerical characteristics of the data raw_data.describe().T """ Explanation: The data doesn't have any null records or any categorical fields. Next, lets check the numerical distribution of the fields. End of explanation """ # plot the correlation matrix plt.figure(figsize=(15, 10)) cols = [ i for i in raw_data.columns if i not in [ "ID", "Cycle", "OpSet3", "SensorMeasure1", "SensorMeasure10", "SensorMeasure18", "SensorMeasure19", ] ] corr_mat = raw_data[cols].corr() matrix = np.triu(corr_mat) sns.heatmap(corr_mat, annot=True, mask=matrix, fmt=".1g") plt.show() """ Explanation: Features OpSet3, SensorMeasure1, SensorMeasure10, SensorMeasure18 & SensorMeasure19 seem to be constant throughout the dataset and thus can be eliminated. Apart from the fields that are constant throughout the data, fields that are correlated highly can also be considered for dropping. Having highly correlated fields in the data often leads to multi-collinearity situation which unnecessarily increases the size of feature-space even if it doesn't affect the accuracy much. Such fields can be identified through correlation-matrices and heatmaps. End of explanation """ cols = [ i for i in cols if i not in [ "SensorMeasure7", "SensorMeasure12", "SensorMeasure20", "SensorMeasure21", "SensorMeasure8", "SensorMeasure11", ] ] corr_mat = raw_data[cols].corr() matrix = np.triu(corr_mat) plt.figure(figsize=(9, 5)) sns.heatmap(corr_mat, annot=True, mask=matrix, fmt=".1g") plt.show() """ Explanation: Fields SensorMeasure7, SensorMeasure12, SensorMeasure20 & SensorMeasure21 correlate highly with many other fields. These fields can be omitted. Further, SensorMeasure8, SensorMeasure11 and SensorMeasure4 seem highly correlated with each other and so any one of them, for example, SensorMeasure4, can be kept and the rest can be omitted. End of explanation """ # get max-cycle of the ids cols = ["ID", "Cycle"] + cols max_cycles_df = ( raw_data.groupby(["ID"], sort=False)["Cycle"] .max() .reset_index() .rename(columns={"Cycle": "MaxCycleID"}) ) # merge back to original dataset FD001_df = pd.merge(raw_data, max_cycles_df, how="inner", on="ID") # calculate rul from max-cycle and current-cycle FD001_df["RUL"] = FD001_df["MaxCycleID"] - FD001_df["Cycle"] """ Explanation: As the current objective is to predict the remaining useful life (RUL) of each unit (ID), the target variable needs to be identified. Since we're dealing with a timeseries data that represents the lifetime of a unit, remaining useful life of a unit can be calculated by subtracting the current cycle from the maximum cycle of that unit. RUL = Max. Cycle - Current Cycle RUL calculation and Feature selection End of explanation """ # plot the RUL vs Cycles one_engine = [] for i, r in FD001_df.iterrows(): rul = r["RUL"] one_engine.append(rul) if rul == 0: plt.plot(one_engine) one_engine = [] plt.grid() """ Explanation: To ensure that the target field is generated properly, the RUL field can be plotted. End of explanation """ # plot feature vs the RUL def plot_feature(feature): plt.figure(figsize=(10, 5)) for i in FD001_df["ID"].unique(): if i % 10 == 0: # only plot every 10th ID plt.plot("RUL", feature, data=FD001_df[FD001_df["ID"] == i]) plt.xlim(250, 0) # reverse the x-axis so RUL counts down to zero plt.xticks(np.arange(0, 275, 25)) plt.ylabel(feature) plt.xlabel("RUL") plt.show() for i in cols: if i not in ["ID", "Cycle"]: plot_feature(i) """ Explanation: The above plot suggests that the RUL, in other words, the remaining cycles, is decreasing as the current cycle increases which is expected. Further, lets see the how the other fields relate to RUL in the current dataset. End of explanation """ # remove the unnecessary fields cols = [ i for i in cols if i not in ["ID", "SensorMeasure5", "SensorMeasure6", "SensorMeasure16"] ] cols """ Explanation: The following set of observations can be made from the outcome of the above cell : - Fields SensorMeasure5 and SensorMeasure16 don't show much variance with the RUL and seem constant all the time. Hence, they can be removed. - Fields SensorMeasure2, SensorMeasure3, SensorMeasure4, SensorMeasure13, SensorMeasure15 & SensorMeasure17 show a similar rising trend. - SensorMeasure9 and SensorMeasure14 show a similar trend. - SensorMeasure6 shows a flatline most of the time except in a very few places and therefore can be ignored. End of explanation """ # split data into train and test X = FD001_df[cols].copy() y = FD001_df["RUL"].copy() # split the data into 70-30 ratio of train-test X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=0.7, random_state=36 ) X_train.shape, y_train.shape, X_test.shape, y_test.shape """ Explanation: Split the data into train and test Divide the dataset with the selected features into train and test sets. End of explanation """ model = xgb.XGBRegressor() model.fit(X_train, y_train) """ Explanation: Fit a regression model <a name="section-6"></a> Initialize and train a regression model using the XGBoost library with the calculated RUL as the target feature. End of explanation """ # print test R2 score y_train_pred = model.predict(X_train) train_score = r2_score(y_train, y_train_pred) y_test_pred = model.predict(X_test) test_score = r2_score(y_test, y_test_pred) print("Train score:", train_score) print("Test score:", test_score) """ Explanation: Evaluate the trained model <a name="section-7"></a> Check the R2 scores of the model on train and test sets. End of explanation """ # print train and test RMSEs train_error = mean_squared_error(y_train, y_train_pred, squared=False) test_error = mean_squared_error(y_test, y_test_pred, squared=False) print("Train error:", train_error) print("Test error:", test_error) """ Explanation: Check the RMSE errors on train and test sets. End of explanation """ # plot the train and test predictions plt.scatter(y_train, y_train_pred) plt.xlabel("Target") plt.ylabel("Prediction") plt.title("Train") plt.show() plt.scatter(y_test, y_test_pred) plt.xlabel("Target") plt.ylabel("Prediction") plt.title("Test") plt.show() """ Explanation: Plot the predicted values against the target values. The closer the plot to a straight line passing through origin with a unit slope, the better the model. End of explanation """ # save the trained model to a local file "model.bst" FILE_NAME = "model.bst" model.save_model(FILE_NAME) """ Explanation: Save the model <a name="section-8"></a> Save the model to a booster file. End of explanation """ # Upload the saved model file to Cloud Storage BLOB_PATH = "mfg_predictive_maintenance/" BLOB_NAME = os.path.join(BLOB_PATH, FILE_NAME) bucket = storage.Client().bucket(BUCKET_NAME) blob = bucket.blob(BLOB_NAME) blob.upload_from_filename(FILE_NAME) """ Explanation: Copy the model to the cloud-storage bucket End of explanation """ ARTIFACT_GCS_PATH = f"gs://{BUCKET_NAME}/{BLOB_PATH}" # Create a Vertex AI model resource aiplatform.init(project=PROJECT_ID, location=REGION) model = aiplatform.Model.upload( display_name=MODEL_DISPLAY_NAME, artifact_uri=ARTIFACT_GCS_PATH, serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/xgboost-cpu.1-1:latest", ) model.wait() print(model.display_name) print(model.resource_name) """ Explanation: Running a notebook end-to-end using executor <a name="section-9"></a> Automating the notebook execution All the steps followed until now can be run as a training job without using any additional code using the Vertex AI Workbench executor. The executor can help you run a notebook file from start to end, with your choice of the environment, machine type, input parameters, and other characteristics. After setting up an execution, the notebook is executed as a job in Vertex AI custom training. Your jobs can be monitored from the Executor pane in the left sidebar. <img src="images/executor.PNG"> The executor also lets you choose the environment and machine type while automating the runs similar to Vertex AI training jobs without switching to the training jobs UI. Apart from the custom container that replicates the existing kernel by default, pre-built environments like TensorFlow Enterprise, PyTorch, and others can also be selected to run the notebook. The required compute power can be specified by choosing from the list of machine types available, including GPUs. Scheduled runs on executor Notebook runs can also be scheduled recurringly with the executor. To do so, select Schedule-based recurring executions as the run type instead of One-time execution. The frequency of the job and the time when it executes is provided when you create the execution. <img src="https://storage.googleapis.com/gweb-cloudblog-publish/images/7_Vertex_AI_Workbench.max-1100x1100.jpg"> Parameterizing the variables The executor lets you run a notebook with different sets of input parameters. If you’ve added parameter tags to any of your notebook cells, you can pass in your parameter values to the executor. More about how to use this feature can be found on this blog. <img src="https://storage.googleapis.com/gweb-cloudblog-publish/images/6_Vertex_AI_Workbench.max-700x700.jpg"> Hosting the model on Vertex AI <a name="section-10"></a> Create a model resource The saved model from the Cloud Storage can be deployed easily using the Vertex AI SDK. To do so, first create a model resource. End of explanation """ endpoint = aiplatform.Endpoint.create(display_name=ENDPOINT_DISPLAY_NAME) print(endpoint.display_name) print(endpoint.resource_name) """ Explanation: Create an Endpoint <a name="section-11"></a> Next, create an endpoint resource for deploying the model. End of explanation """ MACHINE_TYPE = "n1-standard-2" # deploy the model to the endpoint model.deploy( endpoint=endpoint, deployed_model_display_name=DEPLOYED_MODEL_NAME, machine_type=MACHINE_TYPE, ) model.wait() print(model.display_name) print(model.resource_name) """ Explanation: Deploy the model to the created Endpoint <a name="section-12"></a> Configure the deployment name, machine type, and other parameters for the deployment and deploy the model to the created endpoint. End of explanation """ # get predictions on sample data instances = X_test.iloc[0:2].to_numpy().tolist() print(endpoint.predict(instances=instances).predictions) """ Explanation: Test calling the endpoint <a name="section-13"></a> Send some sample data to the deployed model on the endpoint to get predictions. End of explanation """ DEPLOYED_MODEL_ID = "" endpoint.undeploy(deployed_model_id=DEPLOYED_MODEL_ID) """ Explanation: Clean up <a name="section-14"></a> Undeploy the model from the endpoint. End of explanation """ endpoint.delete() """ Explanation: Delete the endpoint. End of explanation """ model.delete() """ Explanation: Delete the model. End of explanation """ ! gsutil -m rm -r $BUCKET_URI """ Explanation: Remove the contents of the Cloud Storage bucket. End of explanation """
EstevesDouglas/UNICAMP-FEEC-IA369Z
dev/checkpoint/2017-04-28-estevesdouglas-compartilhando-notebook.ipynb
gpl-3.0
-- Campainha IoT - LHC - v1.1 -- ESP Inicializa pinos, Configura e Conecta no Wifi, Cria conexão TCP -- e na resposta de um "Tocou" coloca o ESP em modo DeepSleep para economizar bateria. -- Se nenhuma resposta for recebida em 15 segundos coloca o ESP em DeepSleep. led_pin = 3 status_led = gpio.LOW ip_servidor = "192.168.1.10" ip_campainha = "192.168.1.20" voltagem=3333 function desliga_circuito() print("Colocando ESP em Deep Sleep") node.dsleep(0) end function read_voltage() -- Desconecta do wifi para poder ler a voltagem de alimentação do ESP. wifi.sta.disconnect() voltagem = adc.readvdd33() print("Voltagem: "..voltagem) -- Inicializa o Wifi e conecta no servidor print("Inicializando WiFi") init_wifi() end function pisca_led() gpio.write(led_pin, status_led) if status_led == gpio.LOW then status_led = gpio.HIGH else status_led = gpio.LOW end end function init_pins() gpio.mode(led_pin, gpio.OUTPUT) gpio.write(led_pin, status_led) end function init_wifi() wifi.setmode(wifi.STATION) wifi.sta.config("SSID", "password") wifi.sta.connect() wifi.sta.setip({ip=ip_campainha,netmask="255.255.255.0",gateway="192.168.1.1"}) -- Aguarda conexão com Wifi antes de enviar o request. function try_connect() if (wifi.sta.status() == 5) then tmr.stop(0) print("Conectado, mandando request") manda_request() -- Se nenhuma confirmação for recebida em 15 segundos, desliga o ESP. tmr.alarm(2,15000,0, desliga_circuito) else print("Conectando...") end end tmr.alarm(0,1000,1, function() try_connect() end ) end function manda_request() tmr.alarm(1, 200, 1, pisca_led) print("Request enviado") -- Cria a conexão TCP conn=net.createConnection(net.TCP,false) -- Envia o toque da campainha e voltagem para o servidor conn:on("connection", function(conn) conn:send("GET /?bateria=" ..voltagem.. " HTTP/1.0\r\n\r\n") end) -- Se receber "Tocou" do servidor, desliga o ESP. conn:on("receive", function(conn, data) if data:find("Tocou") ~= nil then desliga_circuito() end end) -- Conectar no servidor conn:connect(9999,ip_servidor) end print("Inicializando pinos") init_pins() print ("Lendo voltagem") read_voltage() """ Explanation: IA369Z - Reprodutibilidade em Pesquisa Computacional. Descrição de códigos para devices e coletas Code Client Device ESP8266 Runing program language LUA. End of explanation """ # !/usr/bin/python2 import time import BaseHTTPServer import os import random import string import requests from urlparse import parse_qs, urlparse HOST_NAME = '0.0.0.0' PORT_NUMBER = 9999 # A variável MP3_DIR será construida tendo como base o diretório HOME do usuário + Music/Campainha # (e.g: /home/usuario/Music/Campainha) MP3_DIR = os.path.join(os.getenv('HOME'), 'Music', 'Campainha') VALID_CHARS = set(string.ascii_letters + string.digits + '_.') CHAVE_THINGSPEAK = 'XYZ11ZYX99XYZ1XX' # Salva o arquivo de log no diretório do usuário (e.g: /home/usuário/campainha.log) ARQUIVO_LOG = os.path.join(os.getenv('HOME'), 'campainha.log') def filtra(mp3): if not mp3.endswith('.mp3'): return False for c in mp3: if not c in VALID_CHARS: return False return True def log(msg, output_file=None): if output_file is None: output_file = open(ARQUIVO_LOG, 'a') output_file.write('%s: %s\n' % (time.asctime(), msg)) output_file.flush() class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(s): s.send_header("Content-type", "text/plain") query = urlparse(s.path).query if not query: s.send_response(404) s.end_headers() s.wfile.write('Not found') return components = dict(qc.split('=') for qc in query.split('&')) if not 'bateria' in components: s.send_response(404) s.end_headers() s.wfile.write('Not found') return s.send_response(200) s.end_headers() s.wfile.write('Tocou') s.wfile.flush() log("Atualizando thingspeak") r = requests.post('https://api.thingspeak.com/update', data={'api_key': CHAVE_THINGSPEAK, 'field1': components['bateria']}) log("Thingspeak retornou: %d" % r.status_code) log("Tocando MP3") mp3s = [f for f in os.listdir(MP3_DIR) if filtra(f)] mp3 = random.choice(mp3s) os.system("mpv " + os.path.join(MP3_DIR, mp3)) if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler) log("Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() log("Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)) """ Explanation: Server Local : Runing soun local area. Program Python End of explanation """ import numpy as np import csv with open('database.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: print ', '.join(row) """ Explanation: Export database from dashaboard about device IoT Arquivo csv End of explanation """
feststelltaste/software-analytics
prototypes/_archive/Production Coverage Demo Notebook.ipynb
gpl-3.0
import pandas as pd coverage = pd.read_csv("../input/spring-petclinic/jacoco.csv") coverage = coverage[['PACKAGE', 'CLASS', 'LINE_COVERED' ,'LINE_MISSED']] coverage['LINES'] = coverage.LINE_COVERED + coverage.LINE_MISSED coverage.head(1) """ Explanation: Context John Doe remarked in #AP1432 that there may be too much code in our application that isn't used at all. Before migrating the application to the new platform, we have to analyze which parts of the system are still in use and which are not. Idea To understand how much code isn't used, we recorded the executed code in production with the coverage tool JaCoCo. The measurement took place between 21st Oct 2017 and 27st Oct 2017. The results were exported into a CSV file using the JaCoCo command line tool with the following command: bash java -jar jacococli.jar report "C:\Temp\jacoco.exec" --classfiles \ C:\dev\repos\buschmais-spring-petclinic\target\classes --csv jacoco.csv The CSV file contains all lines of code that were passed through during the measurement's time span. We just take the relevant data and add an additional LINES column to be able to calculate the ratio between covered and missed lines later on. End of explanation """ grouped_by_packages = coverage.groupby("PACKAGE").sum() grouped_by_packages['RATIO'] = grouped_by_packages.LINE_COVERED / grouped_by_packages.LINES grouped_by_packages = grouped_by_packages.sort_values(by='RATIO') grouped_by_packages """ Explanation: Analysis It was stated that whole packages wouldn't be needed anymore and that they could be safely removed. Therefore, we sum up the coverage data per class for each package and calculate the coverage ratio for each package. End of explanation """ %matplotlib inline grouped_by_packages[['RATIO']].plot(kind="barh", figsize=(8,2)) """ Explanation: We plot the data for the coverage ratio to get a brief overview of the result. End of explanation """
yw-fang/readingnotes
machine-learning/Automate-Boring-Staff-Python-2016/ch13.ipynb
apache-2.0
wget https://nostarch.com/download/Automate_the_Boring_Stuff_onlinematerials_v.2.zip """ Explanation: Ch13 处理pdf和wrod文档 2019 July 24 at Kyoto Univ. pdf 和 word 文档都是二进制文件,由于包含多媒体信息(图标甚至视频),处理起来比普通文本复杂许多。好在一些先驱者已经写好了一些模块可以让我们来使用,致敬这帮人!哈哈。这章节我们主要专注从pdf中解析文本,或者从已有文档生成新的pdf。 13.1.1 从 pdf 提取文本 此处我们使用PyPDF2模块,注意它并不能帮助我们提取图像等多媒体信息,不过可以提取文本,并将文本返回为strs。 本书提供了一些文件可以供我们下载。 方便点的话,我们直接在terminal上用 End of explanation """ import PyPDF2 with open('./automate_online-materials/meetingminutes.pdf', 'rb') as f: pdfreader = PyPDF2.PdfFileReader(f) print(pdfreader.numPages) page0 = pdfreader.getPage(0) page0text = page0.extractText() print(page0text) """ Explanation: 就可以下载到,然后可以找到一个叫做meetingminitus.pdf的文件。这个就是我们接下来要用的 End of explanation """ import PyPDF2 with open('./polarmetal-v28-letter.pdf', 'rb') as f: pdfreader = PyPDF2.PdfFileReader(f) print(pdfreader.numPages) for i in range(0,pdfreader.numPages+1): if i==0: page_number = pdfreader.getPage(i) page_text = page_number.extractText() print(page_text[:100]) 所以说,我们并不能期待它太高。标题和姓名中的空格基本上都被‘吞’掉了。这样的话,对于大篇幅文本,可以说并没什么用处。 """ Explanation: 好。现在来试试我自己用latex写的pdf文档。 End of explanation """
spacedrabbit/PythonBootcamp
Advanced Python Objects - Test.ipynb
mit
print bin(1024) print hex(1024) """ Explanation: Advanced Python Objects Test Advanced Numbers Problem 1: Convert 1024 to binary and hexadecimal representation: End of explanation """ print round(5.2322, 2) """ Explanation: Problem 2: Round 5.23222 to two decimal places End of explanation """ s = 'hello how are you Mary, are you feeling okay?' print 'Yup' if s.islower() else 'Nope' """ Explanation: Advanced Strings Problem 3: Check if every letter in the string s is lower case End of explanation """ s = 'twywywtwywbwhsjhwuwshshwuwwwjdjdid' print s.count('w') """ Explanation: Problem 4: How many times does the letter 'w' show up in the string below? End of explanation """ set1 = {2,3,1,5,6,8} set2 = {3,1,7,5,6,8} print set1.difference(set2) # in set 1 but not set 2 print set2.difference(set1) # in set 2 but not set 1 """ Explanation: Advanced Sets Problem 5: Find the elements in set1 that are not in set2: End of explanation """ print set1.union(set2) # all unique elements in either set print set1.intersection(set2) # all elements in both sets """ Explanation: Problem 6: Find all elements that are in either set: End of explanation """ {x:x**3 for x in range(5)} """ Explanation: Advanced Dictionaries Problem 7: Create this dictionary: {0: 0, 1: 1, 2: 8, 3: 27, 4: 64} using dictionary comprehension. End of explanation """ l = [1,2,3,4] l.reverse() # reverses in place, call the list again to check l """ Explanation: Advanced Lists Problem 8: Reverse the list below: End of explanation """ l = [3,4,2,5,1] l.sort() l """ Explanation: Problem 9: Sort the list below End of explanation """
dpshelio/2015-EuroScipy-pandas-tutorial
05 - Time series data.ipynb
bsd-2-clause
%matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt try: import seaborn except: pass pd.options.display.max_rows = 8 """ Explanation: Working with time series data Some imports: End of explanation """ from IPython.display import HTML HTML('<iframe src=http://www.eea.europa.eu/data-and-maps/data/airbase-the-european-air-quality-database-8#tab-data-by-country width=900 height=350></iframe>') """ Explanation: Case study: air quality data of European monitoring stations (AirBase) AirBase (The European Air quality dataBase): hourly measurements of all air quality monitoring stations from Europe. End of explanation """ !head -5 data/airbase_data.csv """ Explanation: I downloaded and preprocessed some of the data (python-airbase): data/airbase_data.csv. This file includes the hourly concentrations of NO2 for 4 different measurement stations: FR04037 (PARIS 13eme): urban background site at Square de Choisy FR04012 (Paris, Place Victor Basch): urban traffic site at Rue d'Alesia BETR802: urban traffic site in Antwerp, Belgium BETN029: rural background site in Houtem, Belgium See http://www.eea.europa.eu/themes/air/interactive/no2 Importing the data Import the csv file: End of explanation """ data = pd.read_csv('data/airbase_data.csv', index_col=0, parse_dates=True, na_values=[-9999]) """ Explanation: As you can see, the missing values are indicated by -9999. This can be recognized by read_csv by passing the na_values keyword: End of explanation """ data.head(3) data.tail() """ Explanation: Exploring the data Some useful methods: head and tail End of explanation """ data.info() """ Explanation: info() End of explanation """ data.describe() """ Explanation: Getting some basic summary statistics about the data with describe: End of explanation """ data.plot(kind='box', ylim=[0,250]) data['BETR801'].plot(kind='hist', bins=50) data.plot(figsize=(12,6)) """ Explanation: Quickly visualizing the data End of explanation """ data[-500:].plot(figsize=(12,6)) """ Explanation: This does not say too much .. We can select part of the data (eg the latest 500 data points): End of explanation """ data.index """ Explanation: Or we can use some more advanced time series features -> next section! Working with time series data When we ensure the DataFrame has a DatetimeIndex, time-series related functionality becomes available: End of explanation """ data["2010-01-01 09:00": "2010-01-01 12:00"] """ Explanation: Indexing a time series works with strings: End of explanation """ data['2012'] """ Explanation: A nice feature is "partial string" indexing, where we can do implicit slicing by providing a partial datetime string. E.g. all data of 2012: End of explanation """ data['2012-01':'2012-03'] """ Explanation: Normally you would expect this to access a column named '2012', but as for a DatetimeIndex, pandas also tries to interprete it as a datetime slice. Or all data of January up to March 2012: End of explanation """ data.index.hour data.index.year """ Explanation: Time and date components can be accessed from the index: End of explanation """ data = data['1999':] """ Explanation: <div class="alert alert-success"> <b>EXERCISE</b>: select all data starting from 1999 </div> End of explanation """ data[data.index.month == 1] """ Explanation: <div class="alert alert-success"> <b>EXERCISE</b>: select all data in January for all different years </div> End of explanation """ data['months'] = data.index.month data[data['months'].isin([1, 2, 3])] """ Explanation: <div class="alert alert-success"> <b>EXERCISE</b>: select all data in January, February and March for all different years </div> End of explanation """ data[(data.index.hour >= 8) & (data.index.hour < 20)] data.between_time('08:00', '20:00') """ Explanation: <div class="alert alert-success"> <b>EXERCISE</b>: select all 'daytime' data (between 8h and 20h) for all days </div> End of explanation """ data.resample('D').head() """ Explanation: The power of pandas: resample A very powerfull method is resample: converting the frequency of the time series (e.g. from hourly to daily data). The time series has a frequency of 1 hour. I want to change this to daily: End of explanation """ data.resample('D', how='max').head() """ Explanation: By default, resample takes the mean as aggregation function, but other methods can also be specified: End of explanation """ data.resample('M').plot() # 'A' # data['2012'].resample('D').plot() """ Explanation: The string to specify the new time frequency: http://pandas.pydata.org/pandas-docs/dev/timeseries.html#offset-aliases These strings can also be combined with numbers, eg '10D'. Further exploring the data: End of explanation """ data.groupby(data.index.year).mean().plot() """ Explanation: <div class="alert alert-success"> <b>QUESTION</b>: plot the monthly mean and median concentration of the 'FR04037' station for the years 2009-2012 </div> <div class="alert alert-success"> <b>QUESTION</b>: plot the monthly mininum and maximum daily concentration of the 'BETR801' station </div> <div class="alert alert-success"> <b>QUESTION</b>: make a bar plot of the mean of the stations in year of 2012 </div> <div class="alert alert-success"> <b>QUESTION</b>: The evolution of the yearly averages with, and the overall mean of all stations? </div> Combination with groupby resample can actually be seen as a specific kind of groupby. E.g. taking annual means with data.resample('A', 'mean') is equivalent to data.groupby(data.index.year).mean() (only the result of resample still has a DatetimeIndex). End of explanation """
GoogleCloudPlatform/tf-estimator-tutorials
08_Text_Analysis/04 - Text Classification - SMS Ham vs. Spam - Word Embeddings + LSTM.ipynb
apache-2.0
import tensorflow as tf from tensorflow import data from datetime import datetime import multiprocessing import shutil print(tf.__version__) MODEL_NAME = 'sms-class-model-01' TRAIN_DATA_FILES_PATTERN = 'data/sms-spam/train-*.tsv' VALID_DATA_FILES_PATTERN = 'data/sms-spam/valid-*.tsv' VOCAB_LIST_FILE = 'data/sms-spam/vocab_list.tsv' N_WORDS_FILE = 'data/sms-spam/n_words.tsv' RESUME_TRAINING = False MULTI_THREADING = True """ Explanation: UCI SMS Spam Collection Dataset Input: sms textual content. Target: ham or spam data representation: each sms is repesented with a fixed-length vector of word indexes. A word index lookup is generated from the vocabulary list. words embedding: A word embedding (dense vector) is learnt for each word. That is, each sms is presented as a matrix of (document-word-count, word-embedding-size) RNN: the embeddings of the words are treated as sequence in an LSTM RNN train-data.tsv, valid-datat.tsv, and vocab_list.tsv are prepared and saved in 'data/sms-spam' End of explanation """ MAX_DOCUMENT_LENGTH = 50 PAD_WORD = '#=KS=#' HEADER = ['class', 'sms'] HEADER_DEFAULTS = [['NA'], ['NA']] TEXT_FEATURE_NAME = 'sms' TARGET_NAME = 'class' WEIGHT_COLUNM_NAME = 'weight' TARGET_LABELS = ['spam', 'ham'] with open(N_WORDS_FILE) as file: N_WORDS = int(file.read())+2 print(N_WORDS) """ Explanation: 1. Define Dataset Metadata End of explanation """ def parse_tsv_row(tsv_row): columns = tf.decode_csv(tsv_row, record_defaults=HEADER_DEFAULTS, field_delim='\t') features = dict(zip(HEADER, columns)) target = features.pop(TARGET_NAME) # giving more weight to "spam" records are the are only 13% of the training set features[WEIGHT_COLUNM_NAME] = tf.cond( tf.equal(target,'spam'), lambda: 6.6, lambda: 1.0 ) return features, target """ Explanation: 2. Define Data Input Function a. TSV parsing logic End of explanation """ def parse_label_column(label_string_tensor): table = tf.contrib.lookup.index_table_from_tensor(tf.constant(TARGET_LABELS)) return table.lookup(label_string_tensor) def input_fn(files_name_pattern, mode=tf.estimator.ModeKeys.EVAL, skip_header_lines=0, num_epochs=1, batch_size=200): shuffle = True if mode == tf.estimator.ModeKeys.TRAIN else False num_threads = multiprocessing.cpu_count() if MULTI_THREADING else 1 buffer_size = 2 * batch_size + 1 print("") print("* data input_fn:") print("================") print("Input file(s): {}".format(files_name_pattern)) print("Batch size: {}".format(batch_size)) print("Epoch Count: {}".format(num_epochs)) print("Mode: {}".format(mode)) print("Thread Count: {}".format(num_threads)) print("Shuffle: {}".format(shuffle)) print("================") print("") file_names = tf.matching_files(files_name_pattern) dataset = data.TextLineDataset(filenames=file_names) dataset = dataset.skip(skip_header_lines) if shuffle: dataset = dataset.shuffle(buffer_size) dataset = dataset.map(lambda tsv_row: parse_tsv_row(tsv_row), num_parallel_calls=num_threads) dataset = dataset.batch(batch_size) dataset = dataset.repeat(num_epochs) dataset = dataset.prefetch(buffer_size) iterator = dataset.make_one_shot_iterator() features, target = iterator.get_next() return features, parse_label_column(target) """ Explanation: b. Data pipeline input function End of explanation """ def process_text(text_feature): # Load vocabolary lookup table to map word => word_id vocab_table = tf.contrib.lookup.index_table_from_file(vocabulary_file=VOCAB_LIST_FILE, num_oov_buckets=1, default_value=-1) # Get text feature smss = text_feature # Split text to words -> this will produce sparse tensor with variable-lengthes (word count) entries words = tf.string_split(smss) # Convert sparse tensor to dense tensor by padding each entry to match the longest in the batch dense_words = tf.sparse_tensor_to_dense(words, default_value=PAD_WORD) # Convert word to word_ids via the vocab lookup table word_ids = vocab_table.lookup(dense_words) # Create a word_ids padding padding = tf.constant([[0,0],[0,MAX_DOCUMENT_LENGTH]]) # Pad all the word_ids entries to the maximum document length word_ids_padded = tf.pad(word_ids, padding) word_id_vector = tf.slice(word_ids_padded, [0,0], [-1, MAX_DOCUMENT_LENGTH]) # Return the final word_id_vector return word_id_vector def model_fn(features, labels, mode, params): hidden_units = params.hidden_units output_layer_size = len(TARGET_LABELS) embedding_size = params.embedding_size forget_bias = params.forget_bias keep_prob = params.keep_prob # word_id_vector word_id_vector = process_text(features[TEXT_FEATURE_NAME]) # print("word_id_vector: {}".format(word_id_vector)) # (?, MAX_DOCUMENT_LENGTH) # layer to take each word_id and convert it into vector (embeddings) word_embeddings = tf.contrib.layers.embed_sequence(word_id_vector, vocab_size=N_WORDS, embed_dim=embedding_size) #print("word_embeddings: {}".format(word_embeddings)) # (?, MAX_DOCUMENT_LENGTH, embbeding_size) # configure the RNN rnn_layers = [tf.nn.rnn_cell.LSTMCell( num_units=size, forget_bias=params.forget_bias, activation=tf.nn.tanh) for size in hparams.hidden_units] # create a RNN cell composed sequentially of a number of RNNCells multi_rnn_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers) input_layer = tf.unstack(word_embeddings, axis=1) # list of len(MAX_DOCUMENT_LENGTH), each element is (?, embbeding_size) #print("input_layer: {}".format(input_layer)) outputs, _ = tf.nn.static_rnn(cell=multi_rnn_cell, inputs=input_layer, dtype=tf.float32) # slice to keep only the last cell of the RNN rnn_output = outputs[-1] # Connect the output layer (logits) to the hidden layer (no activation fn) logits = tf.layers.dense(inputs=rnn_output, units=output_layer_size, activation=None) # print("logits: {}".format(logits)) # (?, output_layer_size) # Provide an estimator spec for `ModeKeys.PREDICT`. if mode == tf.estimator.ModeKeys.PREDICT: probabilities = tf.nn.softmax(logits) predicted_indices = tf.argmax(probabilities, 1) # Convert predicted_indices back into strings predictions = { 'class': tf.gather(TARGET_LABELS, predicted_indices), 'probabilities': probabilities } export_outputs = { 'prediction': tf.estimator.export.PredictOutput(predictions) } # Provide an estimator spec for `ModeKeys.PREDICT` modes. return tf.estimator.EstimatorSpec(mode, predictions=predictions, export_outputs=export_outputs) # weights weights = features[WEIGHT_COLUNM_NAME] # Calculate loss using softmax cross entropy loss = tf.losses.sparse_softmax_cross_entropy( logits=logits, labels=labels, weights=weights ) tf.summary.scalar('loss', loss) if mode == tf.estimator.ModeKeys.TRAIN: # Create Optimiser optimizer = tf.train.AdamOptimizer(params.learning_rate) # Create training operation train_op = optimizer.minimize( loss=loss, global_step=tf.train.get_global_step()) # Provide an estimator spec for `ModeKeys.TRAIN` modes. return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) if mode == tf.estimator.ModeKeys.EVAL: probabilities = tf.nn.softmax(logits) predicted_indices = tf.argmax(probabilities, 1) # Return accuracy and area under ROC curve metrics labels_one_hot = tf.one_hot( labels, depth=len(TARGET_LABELS), on_value=True, off_value=False, dtype=tf.bool ) eval_metric_ops = { 'accuracy': tf.metrics.accuracy(labels, predicted_indices, weights=weights), 'auroc': tf.metrics.auc(labels_one_hot, probabilities, weights=weights) } # Provide an estimator spec for `ModeKeys.EVAL` modes. return tf.estimator.EstimatorSpec(mode, loss=loss, eval_metric_ops=eval_metric_ops) def create_estimator(run_config, hparams): estimator = tf.estimator.Estimator(model_fn=model_fn, params=hparams, config=run_config) print("") print("Estimator Type: {}".format(type(estimator))) print("") return estimator """ Explanation: 3. Define Model Function End of explanation """ TRAIN_SIZE = 4179 NUM_EPOCHS = 100 BATCH_SIZE = 250 EVAL_AFTER_SEC = 60 TOTAL_STEPS = int((TRAIN_SIZE/BATCH_SIZE)*NUM_EPOCHS) hparams = tf.contrib.training.HParams( num_epochs = NUM_EPOCHS, batch_size = BATCH_SIZE, embedding_size = 5, forget_bias=1.0, keep_prob = 0.8, hidden_units=[24, 16], max_steps = TOTAL_STEPS, learning_rate = 0.01 ) model_dir = 'trained_models/{}'.format(MODEL_NAME) run_config = tf.estimator.RunConfig( log_step_count_steps=5000, tf_random_seed=19830610, model_dir=model_dir ) print(hparams) print("Model Directory:", run_config.model_dir) print("") print("Dataset Size:", TRAIN_SIZE) print("Batch Size:", BATCH_SIZE) print("Steps per Epoch:",TRAIN_SIZE/BATCH_SIZE) print("Total Steps:", TOTAL_STEPS) print("That is 1 evaluation step after each",EVAL_AFTER_SEC,"training seconds") """ Explanation: 4. Run Experiment a. Set HParam and RunConfig End of explanation """ def serving_input_fn(): receiver_tensor = { 'sms': tf.placeholder(tf.string, [None]), } features = { key: tensor for key, tensor in receiver_tensor.items() } return tf.estimator.export.ServingInputReceiver( features, receiver_tensor) """ Explanation: b. Define serving function End of explanation """ train_spec = tf.estimator.TrainSpec( input_fn = lambda: input_fn( TRAIN_DATA_FILES_PATTERN, mode = tf.estimator.ModeKeys.TRAIN, num_epochs=hparams.num_epochs, batch_size=hparams.batch_size ), max_steps=hparams.max_steps, hooks=None ) eval_spec = tf.estimator.EvalSpec( input_fn = lambda: input_fn( VALID_DATA_FILES_PATTERN, mode=tf.estimator.ModeKeys.EVAL, batch_size=hparams.batch_size ), exporters=[tf.estimator.LatestExporter( name="predict", # the name of the folder in which the model will be exported to under export serving_input_receiver_fn=serving_input_fn, exports_to_keep=1, as_text=True)], steps=None, throttle_secs = EVAL_AFTER_SEC ) """ Explanation: c. Define TrainSpec and EvaluSpec End of explanation """ if not RESUME_TRAINING: print("Removing previous artifacts...") shutil.rmtree(model_dir, ignore_errors=True) else: print("Resuming training...") tf.logging.set_verbosity(tf.logging.INFO) time_start = datetime.utcnow() print("Experiment started at {}".format(time_start.strftime("%H:%M:%S"))) print(".......................................") estimator = create_estimator(run_config, hparams) tf.estimator.train_and_evaluate( estimator=estimator, train_spec=train_spec, eval_spec=eval_spec ) time_end = datetime.utcnow() print(".......................................") print("Experiment finished at {}".format(time_end.strftime("%H:%M:%S"))) print("") time_elapsed = time_end - time_start print("Experiment elapsed time: {} seconds".format(time_elapsed.total_seconds())) """ Explanation: d. Run Experiment via train_and_evaluate End of explanation """ TRAIN_SIZE = 4179 TEST_SIZE = 1393 train_input_fn = lambda: input_fn(files_name_pattern= TRAIN_DATA_FILES_PATTERN, mode= tf.estimator.ModeKeys.EVAL, batch_size= TRAIN_SIZE) test_input_fn = lambda: input_fn(files_name_pattern= VALID_DATA_FILES_PATTERN, mode= tf.estimator.ModeKeys.EVAL, batch_size= TEST_SIZE) estimator = create_estimator(run_config, hparams) train_results = estimator.evaluate(input_fn=train_input_fn, steps=1) print() print("######################################################################################") print("# Train Measures: {}".format(train_results)) print("######################################################################################") test_results = estimator.evaluate(input_fn=test_input_fn, steps=1) print() print("######################################################################################") print("# Test Measures: {}".format(test_results)) print("######################################################################################") """ Explanation: 5. Evaluate the Model End of explanation """ import os export_dir = model_dir +"/export/predict/" saved_model_dir = export_dir + "/" + os.listdir(path=export_dir)[-1] print(saved_model_dir) print("") predictor_fn = tf.contrib.predictor.from_saved_model( export_dir = saved_model_dir, signature_def_key="prediction" ) output = predictor_fn( { 'sms':[ 'ok, I will be with you in 5 min. see you then', 'win 1000 cash free of charge promo hot deal sexy', 'hot girls sexy tonight call girls waiting for chat' ] } ) print(output) """ Explanation: 6. Predict Using Serving Function End of explanation """
zambzamb/zpic
python/Electron Plasma Waves.ipynb
agpl-3.0
import em1ds as zpic #v_the = 0.001 v_the = 0.02 #v_the = 0.20 electrons = zpic.Species( "electrons", -1.0, ppc = 64, uth=[v_the,v_the,v_the]) sim = zpic.Simulation( nx = 500, box = 50.0, dt = 0.0999/2, species = electrons ) sim.filter_set("sharp", ck = 0.99) #sim.filter_set("gaussian", ck = 50.0) """ Explanation: Electron Plasma Waves Created by Rui Calado and Jorge Vieira, 2018 In this notebook, we are going to study the dispersion relation for electron plasma waves. Theory Electron plasma waves are longitudinal waves that may propagate in unmagnetized plasmas. To derive the dispersion relation for such waves let us start by considering the following setup: * $\nabla\times\mathbf{E}=0$ (Longitudinal waves) * $T_i=T_e=0$ (Cold plasma) * $\mathbf{B}=0$ (Unmagnetized) We start by writing the continuity and momentum equations for the electron and ion species: $$\large \left{\begin{array}{lcr} \frac{\partial n_{e,i}}{\partial t}+\nabla\cdot(n_{e,i}\mathbf{v}{e,i})=0 \ \frac{\partial \mathbf{v}{e,i}}{\partial t}=\mp \frac{e}{m_{e,i}}\mathbf{E}\ \end{array}\right. . $$ Then we consider Poisson's equation: $$\epsilon_0\nabla\cdot\mathbf{E}=e(n_i-n_e).$$ Applying a time derivative twice, $$\epsilon_0\nabla\cdot\left(\frac{\partial^2 \mathbf{E}}{\partial t^2}\right)=e\left(\frac{\partial^2n_i}{\partial t^2}-\frac{\partial^2n_e}{\partial t^2}\right).$$ Using the continuity and momentum equations we get: $$\frac{\partial^2 \mathbf{E}}{\partial t^2}-\frac{e^2n_0}{\epsilon_0}\left(\frac{1}{m_i}+\frac{1}{m_e}\right)\mathbf{E}=0.$$ This is the equation for a harmonic oscillator. Neglecting the $1/m_i$ term since $m_e\ll m_i$, our oscillation frequency is the electron plasma frequency: $$\omega=\frac{e^2n_0}{\epsilon_0 m_e}\equiv \omega_{p}.$$ Warm plasma Now, what happens if we consider a warm plasma instead? Neglecting ion motion, the first step is to add a pressure term to the electron momentum equation: $$\frac{\partial \mathbf{v}{e}}{\partial t}=- \frac{e}{m{e}}\mathbf{E}-\frac{\gamma k_BT_e}{m_en_0}\nabla n_1.$$ We also note that Poisson's equation now takes the form: $$\nabla\cdot\mathbf{E}=-\frac{e}{\epsilon_0}n_1.$$ Taking the divergence of the momentum equation, we get: $$\nabla\cdot\left( \frac{\partial \mathbf{v}}{\partial t} \right)=-\frac{e}{m_e}\nabla\cdot\mathbf{E}-\frac{\gamma kT_e}{m_en_0}\nabla\cdot (\nabla n_e).$$ Using the unchanged continuity equation and Poisson's equation: $$\frac{\partial^2n_1}{\partial t^2}+\omega_{p}^2n_1-\frac{\gamma k_BT_e}{m_e}\nabla\cdot(\nabla n_1)=0.$$ Considering the high frequency regime, there will be no heat losses in our time scale, and so we will take the adiabatic coefficient $\gamma=3$ for 1D longitudinal oscillations. Additionally, we use the definition $v_{th}^2=k_BT_e/m_e$ to write: $$\frac{\partial^2n_1}{\partial t^2}+\omega_{p}^2n_1-3v_{th}^2\nabla\cdot(\nabla n_1)=0.$$ The final step consists of considering sinusoidal waves such that $n_1=\text{n}_1\exp^{i(\mathbf{k}\cdot\mathbf{r}-\omega t)}$ and then Fourier analyzing the equation $\left(\nabla=i\mathbf{k},\ \frac{\partial}{\partial t}=-i\omega \right)$, which results in the dispersion relation: $$\omega^2=\omega_{p}^2+3v_{th}^2k^2.$$ Simulations with ZPIC End of explanation """ import numpy as np niter = 4000 Ex_t = np.zeros((niter,sim.nx)) Ez_t = np.zeros((niter,sim.nx)) tmax = niter * sim.dt print("\nRunning simulation up to t = {:g} ...".format(tmax)) while sim.t <= tmax: print('n = {:d}, t = {:g}'.format(sim.n,sim.t), end = '\r') Ex_t[sim.n,:] = sim.emf.Ex Ez_t[sim.n,:] = sim.emf.Ez sim.iter() print("\nDone.") """ Explanation: We run the simulation up to a fixed number of iterations, controlled by the variable niter, storing the value of the EM field $E_z$ at every timestep so we can analyze them later: End of explanation """ import matplotlib.pyplot as plt iter = sim.n//2 plt.plot(np.linspace(0, sim.box, num = sim.nx),Ex_t[iter,:], label = "$E_x$") plt.plot(np.linspace(0, sim.box, num = sim.nx),Ez_t[iter,:], label = "$E_z$") plt.grid(True) plt.xlabel("$x_1$ [$c/\omega_n$]") plt.ylabel("$E$ field []") plt.title("$E_x$, $E_z$, t = {:g}".format( iter * sim.dt)) plt.legend() plt.show() """ Explanation: Electrostatic / Electromagnetic Waves As discussed above, the simulation was initialized with a broad spectrum of waves through the thermal noise of the plasma. We can see the noisy fields in the plot below: End of explanation """ import matplotlib.pyplot as plt import matplotlib.colors as colors # (omega,k) power spectrum win = np.hanning(niter) for i in range(sim.nx): Ex_t[:,i] *= win sp = np.abs(np.fft.fft2(Ex_t))**2 sp = np.fft.fftshift( sp ) k_max = np.pi / sim.dx omega_max = np.pi / sim.dt plt.imshow( sp, origin = 'lower', norm=colors.LogNorm(vmin = 1.0), extent = ( -k_max, k_max, -omega_max, omega_max ), aspect = 'auto', cmap = 'gray') k = np.linspace(-k_max, k_max, num = 512) w=np.sqrt(1 + 3 * v_the**2 * k**2) plt.plot( k, w, label = "Electron Plasma Wave", color = 'r',ls = '-.' ) plt.ylim(0,2) plt.xlim(0,k_max) plt.xlabel("$k$ [$\omega_n/c$]") plt.ylabel("$\omega$ [$\omega_n$]") plt.title("Wave dispersion relation") plt.legend() plt.show() """ Explanation: Electrostatic Plasma Waves To analyze the dispersion relation of the electrostatic plasma waves we use a 2D (Fast) Fourier transform of $E_x(x,t)$ field values that we stored during the simulation. The plot below shows the obtained power spectrum alongside the theoretical prediction. Since the dataset is not periodic along $t$ we apply a windowing technique (Hanning) to the dataset to lower the background spectrum, and make the dispersion relation more visible. End of explanation """ import matplotlib.pyplot as plt import matplotlib.colors as colors # (omega,k) power spectrum win = np.hanning(niter) for i in range(sim.nx): Ez_t[:,i] *= win sp = np.abs(np.fft.fft2(Ez_t))**2 sp = np.fft.fftshift( sp ) k_max = np.pi / sim.dx omega_max = np.pi / sim.dt plt.imshow( sp, origin = 'lower', norm=colors.LogNorm(vmin = 1e-5, vmax = 0.01), extent = ( -k_max, k_max, -omega_max, omega_max ), aspect = 'auto', cmap = 'gray') k = np.linspace(-k_max, k_max, num = 512) w=np.sqrt(1 + k**2) plt.plot( k, w, label = "$\omega^2 = \omega_p^2 + k^2 c^2$", color = 'r', ls = '-.' ) plt.ylim(0,k_max) plt.xlim(0,k_max) plt.xlabel("$k$ [$\omega_n/c$]") plt.ylabel("$\omega$ [$\omega_n$]") plt.title("EM-wave dispersion relation") plt.legend() plt.show() """ Explanation: Electromagnetic Plasma Waves To analyze the dispersion relation of the electrostatic plasma waves we use a 2D (Fast) Fourier transform of $E_z(x,t)$ field values that we stored during the simulation. The plot below shows the obtained power spectrum alongside the theoretical prediction. Since the dataset is not periodic along $t$ we apply a windowing technique (Hanning) to the dataset to lower the background spectrum, and make the dispersion relation more visible. End of explanation """
sandeshkalantre/bdg-nanowire
Arahanov-Bohm Oscillations/Cylindrical Shell and Arahanov-Bohm Oscillations.ipynb
mit
import numpy as np import matplotlib.pyplot as plt %matplotlib inline import itertools import scipy.special # define a dummy class to pass parameters to functions class Parameters: def __init__(self): return # define the Hamiltonian def calc_H(params): t_z = params.t_z t_phi = params.t_phi N_z = params.N_z N_phi = params.N_phi flux = params.flux mu = params.mu indices = list(itertools.product(range(N_z),range(N_phi))) def calc_H_element(x,y): if x == y: return 2*t_z + abs(t_phi)*(2 + (2*np.pi*flux/N_phi)**2) - mu elif (x[1]-y[1] == 1 or x[1]-y[1] == N_phi - 1) and x[0] == y[0]: return -t_phi elif (x[1]-y[1] == -1 or x[1]-y[1] == -N_phi + 1) and x[0] == y[0]: return -np.conj(t_phi) elif x[1] == y[1] and abs(x[0]-y[0]) == 1: return -t_z else: return 0.0 # no messy flattening problem as compared to 2x2 Nambu matrices in BdG H_array = np.matrix(np.array([calc_H_element(x,y) for x in indices for y in indices]).reshape(N_phi*N_z,N_phi*N_z)) return H_array def calc_DOS(E,H): eta = 1e-2 G = np.linalg.inv((E+1j*eta)*np.eye(H.shape[0]) - H) A = 1j*(G - np.conj(G).T) dos = np.real(np.trace(A)) return dos """ Explanation: Cylindrical Ring and Arahanov-Bohm Oscillations I will use this notebook to study the DOS of a cylindrical conducting shell made of normal material. The aim is to reproduce the angular momemtum subband structure. Once the DOS looks good, I will add an axial magnetic field in the system and see how it affects the sub-band structure. The final step is to reproduce Arahanov-Bohm conductance oscillations using NEGF. End of explanation """ params = Parameters() params.t_z = 1 params.flux = 0 params.t_phi = 1*np.exp(1j*2*np.pi*params.flux) params.N_z = 1 params.N_phi = 50 params.mu = 2 H = calc_H(params) E_linspace = np.linspace(-4,6,10000) dos = np.array([calc_DOS(E,H) for E in E_linspace]) plt.plot(E_linspace,dos) plt.xlabel('Energy (E)') plt.ylabel('Density of States(E) [a.u.]') """ Explanation: I will now simulate a thick nanowire with less points in the length and more points in the circumference. The different l sub-bands are observed. End of explanation """ for i in range(10): params = Parameters() params.N_z = 1 params.N_phi = 50 params.flux = 5*i params.t_z = 1 params.t_phi = 1*np.exp(1j*2*np.pi*params.flux/N_phi) params.mu = 2 H = calc_H(params) E_linspace = np.linspace(0,4,1000) dos = np.array([calc_DOS(E,H) for E in E_linspace]) #plt.figure(i) plt.plot(E_linspace,dos) plt.xlabel('Energy (E)') plt.ylabel('Density of States(E) [a.u.]') #plt.title("flux" + str(params.flux)) # code for transport def calc_current(E,params): if params.N_z < 2: raise Exception("Calculation of current requires atleast two logitudianl points in the device.") eta = 1e-10 # calcualtion of the surface functions def surface_g(E,parmas): dummy_contact_params = Parameters() dummy_contact_params.N_z = 2 dummy_contact_params.N_phi = params.N_phi dummy_contact_params.flux = params.flux dummy_contact_params.t_z = params.t_z dummy_contact_params.t_phi = params.t_phi dummy_contact_params.mu = params.mu H_mat = calc_H(dummy_contact_params) N_dof_lat = params.N_phi alpha = H_mat[:N_dof_lat,:N_dof_lat] beta = H_mat[:N_dof_lat,N_dof_lat:2*N_dof_lat] err = 1.0 iter_count = 0 iter_limit = 100000 err_limit = 1e-6 g = np.linalg.inv((E + 1j*eta)*np.eye(alpha.shape[0]) - alpha) g_old = np.linalg.inv((E + 1j*eta)*np.eye(alpha.shape[0]) - alpha) # iterate over iter_limit iterations or until err < err_limit for i in range(iter_limit): g = np.linalg.inv((E + 1j*eta)*np.eye(alpha.shape[0]) - alpha - np.dot(np.dot(np.conj(beta.T),g),beta)) g = 0.5*(g + g_old) err = np.linalg.norm(g-g_old)/np.sqrt(np.linalg.norm(g)*np.linalg.norm(g_old)) g_old = g if(err < err_limit): #print("Finished at",i,"Error :",err) break; if(i == (iter_limit - 1)): print("iter_limit hit in calculation of surface_g",err) return np.matrix(g) g_1 = surface_g(E,params) g_2 = surface_g(E,params) H_mat = calc_H(params) #number of dof in a layer N_dof_lat = params.N_phi # the hopping element between layers beta_layer = H_mat[:N_dof_lat,N_dof_lat:2*N_dof_lat] # the only non-zero elements in sigma sigma_mini_1 = beta_layer.H @ g_1 @ beta_layer sigma_mini_2 = beta_layer.H @ g_2 @ beta_layer sigma_1 = np.matrix(np.zeros(H_mat.shape,dtype=np.complex64)) sigma_1[:N_dof_lat,:N_dof_lat] = sigma_mini_1 gamma_1 = 1j*(sigma_1 - sigma_1.H) sigma_2 = np.matrix(np.zeros(H_mat.shape,dtype=np.complex64)) sigma_2[-N_dof_lat:,-N_dof_lat:] = sigma_mini_2 gamma_2 = 1j*(sigma_2 - sigma_2.H) def fermi(E,kT): return scipy.special.expit(-E/kT) kT = params.kT N_phi = params.N_phi N_z = params.N_z mu = params.mu sigma_in = fermi(E-mu,kT)*gamma_1 + fermi(E-mu,kT)*gamma_2 G = np.matrix(np.linalg.inv((E + 1j*eta)*np.eye(H_mat.shape[0]) - H_mat - sigma_1 - sigma_2)) #G_n = G @ sigma_in @ G.H T = np.real(np.trace(gamma_1 @ G @ gamma_2 @ G.H)) return T params = Parameters() params.N_z = 2 params.N_phi = 50 params.flux = 0 params.t_z = 1 params.t_phi = 1*np.exp(1j*2*np.pi*params.flux/params.N_phi) params.mu = 0 params.kT = 1e-5 E_linspace = np.linspace(0,8,100) I = np.array([calc_current(E,params) for E in E_linspace]) plt.figure(i) plt.plot(E_linspace,I) plt.xlabel('Energy (E)') plt.title("Transmission at flux " + str(params.flux)) """ Explanation: I now want to introduce a magnetic field in the simulation. I think one way to do it is to add a phase to t_phi parameter. End of explanation """ def calc_T(flux): print("Flux : ",flux) params = Parameters() params.N_z = 2 params.N_phi = 30 params.flux = flux params.t_z = 1 params.t_phi = 1*np.exp(1j*2*np.pi*params.flux/params.N_phi) params.mu = 0 params.kT = 1e-3 E_linspace = np.linspace(0,8,100) T = np.array([calc_current(E,params) for E in E_linspace]) return T T_map = np.array([calc_T(flux) for flux in np.linspace(0,6,100)]) XX,YY = np.meshgrid(np.linspace(0,6,100),np.linspace(0,8,100)) plt.figure(1) plt.pcolor(XX,YY,T_map.T,cmap="coolwarm") plt.xlabel(r"$\frac{\Phi}{\Phi_0}$",fontsize=16) plt.ylabel("Energy/t",fontsize=16) cbar = plt.colorbar() cbar.set_label('Transmission (T) [a.u.]') plt.plot(T_map.T[70,:]) """ Explanation: I am studying the variation of T near the Fermi level. Transmission function map Transmission function map is T calculated as a function of the energy and the flux. End of explanation """
plumbwj01/Barcoding-Fraxinus
scanfasta.ipynb
apache-2.0
desired_contigs = ['Contig' + str(x) for x in [1131, 3182, 39106, 110, 5958]] desired_contigs """ Explanation: Using the two contig names you sent me it's simplest to do this: End of explanation """ grab = [c for c in contigs if c.name in desired_contigs] len(grab) """ Explanation: If you have a genuinely big file then I would do the following: End of explanation """ import os print(os.getcwd()) write_contigs_to_file('data2/sequences_desired.fa', grab) [c.name for c in grab[:100]] import os os.path.realpath('') """ Explanation: Ya! There's two contigs. End of explanation """
ageron/ml-notebooks
09_up_and_running_with_tensorflow.ipynb
apache-2.0
# To support both python 2 and python 3 from __future__ import division, print_function, unicode_literals # Common imports import numpy as np import os try: # %tensorflow_version only exists in Colab. %tensorflow_version 1.x except Exception: pass # to make this notebook's output stable across runs def reset_graph(seed=42): tf.reset_default_graph() tf.set_random_seed(seed) np.random.seed(seed) # To plot pretty figures %matplotlib inline import matplotlib import matplotlib.pyplot as plt plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 # Where to save the figures PROJECT_ROOT_DIR = "." CHAPTER_ID = "tensorflow" IMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID) os.makedirs(IMAGES_PATH, exist_ok=True) def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300): path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension) print("Saving figure", fig_id) if tight_layout: plt.tight_layout() plt.savefig(path, format=fig_extension, dpi=resolution) """ Explanation: Chapter 9 – Up and running with TensorFlow This notebook contains all the sample code and solutions to the exercises in chapter 9. <table align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/ageron/handson-ml/blob/master/09_up_and_running_with_tensorflow.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> </table> Warning: this is the code for the 1st edition of the book. Please visit https://github.com/ageron/handson-ml2 for the 2nd edition code, with up-to-date notebooks using the latest library versions. In particular, the 1st edition is based on TensorFlow 1, while the 2nd edition uses TensorFlow 2, which is much simpler to use. Setup First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures: End of explanation """ import tensorflow as tf reset_graph() x = tf.Variable(3, name="x") y = tf.Variable(4, name="y") f = x*x*y + y + 2 f sess = tf.Session() sess.run(x.initializer) sess.run(y.initializer) result = sess.run(f) print(result) sess.close() with tf.Session() as sess: x.initializer.run() y.initializer.run() result = f.eval() result init = tf.global_variables_initializer() with tf.Session() as sess: init.run() result = f.eval() result init = tf.global_variables_initializer() sess = tf.InteractiveSession() init.run() result = f.eval() print(result) sess.close() result """ Explanation: Creating and running a graph End of explanation """ reset_graph() x1 = tf.Variable(1) x1.graph is tf.get_default_graph() graph = tf.Graph() with graph.as_default(): x2 = tf.Variable(2) x2.graph is graph x2.graph is tf.get_default_graph() w = tf.constant(3) x = w + 2 y = x + 5 z = x * 3 with tf.Session() as sess: print(y.eval()) # 10 print(z.eval()) # 15 with tf.Session() as sess: y_val, z_val = sess.run([y, z]) print(y_val) # 10 print(z_val) # 15 """ Explanation: Managing graphs End of explanation """ import numpy as np from sklearn.datasets import fetch_california_housing reset_graph() housing = fetch_california_housing() m, n = housing.data.shape housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data] X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name="X") y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") XT = tf.transpose(X) theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(XT, X)), XT), y) with tf.Session() as sess: theta_value = theta.eval() theta_value """ Explanation: Linear Regression Using the Normal Equation End of explanation """ X = housing_data_plus_bias y = housing.target.reshape(-1, 1) theta_numpy = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) print(theta_numpy) """ Explanation: Compare with pure NumPy End of explanation """ from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(housing.data, housing.target.reshape(-1, 1)) print(np.r_[lin_reg.intercept_.reshape(-1, 1), lin_reg.coef_.T]) """ Explanation: Compare with Scikit-Learn End of explanation """ from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaled_housing_data = scaler.fit_transform(housing.data) scaled_housing_data_plus_bias = np.c_[np.ones((m, 1)), scaled_housing_data] print(scaled_housing_data_plus_bias.mean(axis=0)) print(scaled_housing_data_plus_bias.mean(axis=1)) print(scaled_housing_data_plus_bias.mean()) print(scaled_housing_data_plus_bias.shape) """ Explanation: Using Batch Gradient Descent Gradient Descent requires scaling the feature vectors first. We could do this using TF, but let's just use Scikit-Learn for now. End of explanation """ reset_graph() n_epochs = 1000 learning_rate = 0.01 X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") gradients = 2/m * tf.matmul(tf.transpose(X), error) training_op = tf.assign(theta, theta - learning_rate * gradients) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): if epoch % 100 == 0: print("Epoch", epoch, "MSE =", mse.eval()) sess.run(training_op) best_theta = theta.eval() best_theta """ Explanation: Manually computing the gradients End of explanation """ reset_graph() n_epochs = 1000 learning_rate = 0.01 X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") gradients = tf.gradients(mse, [theta])[0] training_op = tf.assign(theta, theta - learning_rate * gradients) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): if epoch % 100 == 0: print("Epoch", epoch, "MSE =", mse.eval()) sess.run(training_op) best_theta = theta.eval() print("Best theta:") print(best_theta) """ Explanation: Using autodiff Same as above except for the gradients = ... line: End of explanation """ def my_func(a, b): z = 0 for i in range(100): z = a * np.cos(z + i) + z * np.sin(b - i) return z my_func(0.2, 0.3) reset_graph() a = tf.Variable(0.2, name="a") b = tf.Variable(0.3, name="b") z = tf.constant(0.0, name="z0") for i in range(100): z = a * tf.cos(z + i) + z * tf.sin(b - i) grads = tf.gradients(z, [a, b]) init = tf.global_variables_initializer() """ Explanation: How could you find the partial derivatives of the following function with regards to a and b? End of explanation """ with tf.Session() as sess: init.run() print(z.eval()) print(sess.run(grads)) """ Explanation: Let's compute the function at $a=0.2$ and $b=0.3$, and the partial derivatives at that point with regards to $a$ and with regards to $b$: End of explanation """ reset_graph() n_epochs = 1000 learning_rate = 0.01 X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(mse) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): if epoch % 100 == 0: print("Epoch", epoch, "MSE =", mse.eval()) sess.run(training_op) best_theta = theta.eval() print("Best theta:") print(best_theta) """ Explanation: Using a GradientDescentOptimizer End of explanation """ reset_graph() n_epochs = 1000 learning_rate = 0.01 X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9) training_op = optimizer.minimize(mse) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): sess.run(training_op) best_theta = theta.eval() print("Best theta:") print(best_theta) """ Explanation: Using a momentum optimizer End of explanation """ reset_graph() A = tf.placeholder(tf.float32, shape=(None, 3)) B = A + 5 with tf.Session() as sess: B_val_1 = B.eval(feed_dict={A: [[1, 2, 3]]}) B_val_2 = B.eval(feed_dict={A: [[4, 5, 6], [7, 8, 9]]}) print(B_val_1) print(B_val_2) """ Explanation: Feeding data to the training algorithm Placeholder nodes End of explanation """ n_epochs = 1000 learning_rate = 0.01 reset_graph() X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X") y = tf.placeholder(tf.float32, shape=(None, 1), name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(mse) init = tf.global_variables_initializer() n_epochs = 10 batch_size = 100 n_batches = int(np.ceil(m / batch_size)) def fetch_batch(epoch, batch_index, batch_size): np.random.seed(epoch * n_batches + batch_index) # not shown in the book indices = np.random.randint(m, size=batch_size) # not shown X_batch = scaled_housing_data_plus_bias[indices] # not shown y_batch = housing.target.reshape(-1, 1)[indices] # not shown return X_batch, y_batch with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): for batch_index in range(n_batches): X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) best_theta = theta.eval() best_theta """ Explanation: Mini-batch Gradient Descent End of explanation """ reset_graph() n_epochs = 1000 # not shown in the book learning_rate = 0.01 # not shown X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name="X") # not shown y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name="y") # not shown theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") # not shown error = y_pred - y # not shown mse = tf.reduce_mean(tf.square(error), name="mse") # not shown optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) # not shown training_op = optimizer.minimize(mse) # not shown init = tf.global_variables_initializer() saver = tf.train.Saver() with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): if epoch % 100 == 0: print("Epoch", epoch, "MSE =", mse.eval()) # not shown save_path = saver.save(sess, "/tmp/my_model.ckpt") sess.run(training_op) best_theta = theta.eval() save_path = saver.save(sess, "/tmp/my_model_final.ckpt") best_theta with tf.Session() as sess: saver.restore(sess, "/tmp/my_model_final.ckpt") best_theta_restored = theta.eval() # not shown in the book np.allclose(best_theta, best_theta_restored) """ Explanation: Saving and restoring a model End of explanation """ saver = tf.train.Saver({"weights": theta}) """ Explanation: If you want to have a saver that loads and restores theta with a different name, such as "weights": End of explanation """ reset_graph() # notice that we start with an empty graph. saver = tf.train.import_meta_graph("/tmp/my_model_final.ckpt.meta") # this loads the graph structure theta = tf.get_default_graph().get_tensor_by_name("theta:0") # not shown in the book with tf.Session() as sess: saver.restore(sess, "/tmp/my_model_final.ckpt") # this restores the graph's state best_theta_restored = theta.eval() # not shown in the book np.allclose(best_theta, best_theta_restored) """ Explanation: By default the saver also saves the graph structure itself in a second file with the extension .meta. You can use the function tf.train.import_meta_graph() to restore the graph structure. This function loads the graph into the default graph and returns a Saver that can then be used to restore the graph state (i.e., the variable values): End of explanation """ from datetime import datetime now = datetime.utcnow().strftime("%Y%m%d%H%M%S") root_logdir = "tf_logs" logdir = "{}/run-{}/".format(root_logdir, now) logdir """ Explanation: This means that you can import a pretrained model without having to have the corresponding Python code to build the graph. This is very handy when you keep tweaking and saving your model: you can load a previously saved model without having to search for the version of the code that built it. Visualizing the graph TensorBoard is a great tool to visualize TensorFlow graphs, training curves, and much more. Our TensorFlow code will write various files in a log directory, and the TensorBoard server will regularly read these files and produce nice interactive visualizations. It can plot graphs, learning curves (i.e., how the loss evaluated on the training set or test set evolves as a function of the epoch number), profiling data to identify performance bottlenecks, and more. In short, it helps keep track of everything. Here's the overall picture: TensorFlow writes logs to ===&gt; log directory ===&gt; TensorBoard reads data and displays visualizations If we want to visualize different graphs, or learning curves for different training runs, we don't want the log files to get all mixed up. So we will need one log subdirectory per graph, or per run. Let's use a root log directory that we will call tf_logs, and a sub-directory that we will call run- followed by the current timestamp (you can use any other name you prefer in your own code): End of explanation """ def make_log_subdir(run_id=None): if run_id is None: run_id = datetime.utcnow().strftime("%Y%m%d%H%M%S") return "{}/run-{}/".format(root_logdir, run_id) """ Explanation: In fact, let's create a function that will generate such a subdirectory path every time we need one: End of explanation """ file_writer = tf.summary.FileWriter(logdir, graph=tf.get_default_graph()) """ Explanation: Now let's save the default graph to our log subdirectory using tf.summary.FileWriter(): End of explanation """ os.listdir(root_logdir) """ Explanation: Now the root log directory contains one subdirectory: End of explanation """ os.listdir(logdir) """ Explanation: And this subdirectory contains one log file (called a "TF events" file) for the graph: End of explanation """ file_writer.close() """ Explanation: However, the actual graph data may still be in the OS's file cache, so we need to flush() or close() the FileWriter to be sure that it's well written to disk: End of explanation """ %load_ext tensorboard """ Explanation: Okay, now let's start TensorBoard! It runs as a web server in a separate process, so we first need to start it. One way to do that is to run the tensorboard command in a terminal window. Another is to use the %tensorboard Jupyter extension, which takes care of starting TensorBoard, and it allows us to view TensorBoard's user interface directly within Jupyter. Let's load this extension now: End of explanation """ %tensorboard --logdir {root_logdir} """ Explanation: Next, let's use the %tensorboard extension to start the TensorBoard server. We need to point it to the root log directory: End of explanation """ def save_graph(graph=None, run_id=None): if graph is None: graph = tf.get_default_graph() logdir = make_log_subdir(run_id) file_writer = tf.summary.FileWriter(logdir, graph=graph) file_writer.close() return logdir """ Explanation: Great! We can now visualize graphs. :) In fact, let's make this easy by creating a save_graph() function that will automatically create a new log subdir and save the given graph (by default tf.get_default_graph()) to this directory: End of explanation """ save_graph() """ Explanation: Let's see if it works: End of explanation """ %tensorboard --logdir {root_logdir} """ Explanation: Now let's look at TensorBoard again. Note that this will reuse the existing TensorBoard server since we're reusing the same root log directory: End of explanation """ reset_graph() n_epochs = 1000 learning_rate = 0.01 X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X") y = tf.placeholder(tf.float32, shape=(None, 1), name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(mse) init = tf.global_variables_initializer() logdir = make_log_subdir() mse_summary = tf.summary.scalar('MSE', mse) file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph()) n_epochs = 10 batch_size = 100 n_batches = int(np.ceil(m / batch_size)) with tf.Session() as sess: # not shown in the book sess.run(init) # not shown for epoch in range(n_epochs): # not shown for batch_index in range(n_batches): X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size) if batch_index % 10 == 0: summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch}) step = epoch * n_batches + batch_index file_writer.add_summary(summary_str, step) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) best_theta = theta.eval() # not shown file_writer.close() best_theta """ Explanation: Notice that you can switch between runs by picking the log subdirectory you want from the "Run" dropdown list (at the top left). Visualizing Learning Curves Now let's see how to visualize learning curves: End of explanation """ %tensorboard --logdir {root_logdir} """ Explanation: Now let's look at TensorBoard. Try going to the SCALARS tab: End of explanation """ reset_graph() n_epochs = 1000 learning_rate = 0.01 X = tf.placeholder(tf.float32, shape=(None, n + 1), name="X") y = tf.placeholder(tf.float32, shape=(None, 1), name="y") theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0, seed=42), name="theta") y_pred = tf.matmul(X, theta, name="predictions") with tf.name_scope("loss") as scope: error = y_pred - y mse = tf.reduce_mean(tf.square(error), name="mse") optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(mse) init = tf.global_variables_initializer() mse_summary = tf.summary.scalar('MSE', mse) logdir = make_log_subdir() file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph()) n_epochs = 10 batch_size = 100 n_batches = int(np.ceil(m / batch_size)) with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): for batch_index in range(n_batches): X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size) if batch_index % 10 == 0: summary_str = mse_summary.eval(feed_dict={X: X_batch, y: y_batch}) step = epoch * n_batches + batch_index file_writer.add_summary(summary_str, step) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) best_theta = theta.eval() file_writer.flush() file_writer.close() print("Best theta:") print(best_theta) print(error.op.name) print(mse.op.name) reset_graph() a1 = tf.Variable(0, name="a") # name == "a" a2 = tf.Variable(0, name="a") # name == "a_1" with tf.name_scope("param"): # name == "param" a3 = tf.Variable(0, name="a") # name == "param/a" with tf.name_scope("param"): # name == "param_1" a4 = tf.Variable(0, name="a") # name == "param_1/a" for node in (a1, a2, a3, a4): print(node.op.name) """ Explanation: Name scopes End of explanation """ reset_graph() n_features = 3 X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") w1 = tf.Variable(tf.random_normal((n_features, 1)), name="weights1") w2 = tf.Variable(tf.random_normal((n_features, 1)), name="weights2") b1 = tf.Variable(0.0, name="bias1") b2 = tf.Variable(0.0, name="bias2") z1 = tf.add(tf.matmul(X, w1), b1, name="z1") z2 = tf.add(tf.matmul(X, w2), b2, name="z2") relu1 = tf.maximum(z1, 0., name="relu1") relu2 = tf.maximum(z1, 0., name="relu2") # Oops, cut&paste error! Did you spot it? output = tf.add(relu1, relu2, name="output") """ Explanation: Modularity An ugly flat code: End of explanation """ reset_graph() def relu(X): w_shape = (int(X.get_shape()[1]), 1) w = tf.Variable(tf.random_normal(w_shape), name="weights") b = tf.Variable(0.0, name="bias") z = tf.add(tf.matmul(X, w), b, name="z") return tf.maximum(z, 0., name="relu") n_features = 3 X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") relus = [relu(X) for i in range(5)] output = tf.add_n(relus, name="output") save_graph(run_id="relu1") %tensorboard --logdir {root_logdir} """ Explanation: Much better, using a function to build the ReLUs: End of explanation """ reset_graph() def relu(X): with tf.name_scope("relu"): w_shape = (int(X.get_shape()[1]), 1) # not shown in the book w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown b = tf.Variable(0.0, name="bias") # not shown z = tf.add(tf.matmul(X, w), b, name="z") # not shown return tf.maximum(z, 0., name="max") # not shown n_features = 3 X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") relus = [relu(X) for i in range(5)] output = tf.add_n(relus, name="output") save_graph(run_id="relu2") %tensorboard --logdir {root_logdir} """ Explanation: Even better using name scopes: End of explanation """ reset_graph() def relu(X, threshold): with tf.name_scope("relu"): w_shape = (int(X.get_shape()[1]), 1) # not shown in the book w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown b = tf.Variable(0.0, name="bias") # not shown z = tf.add(tf.matmul(X, w), b, name="z") # not shown return tf.maximum(z, threshold, name="max") threshold = tf.Variable(0.0, name="threshold") X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") relus = [relu(X, threshold) for i in range(5)] output = tf.add_n(relus, name="output") reset_graph() def relu(X): with tf.name_scope("relu"): if not hasattr(relu, "threshold"): relu.threshold = tf.Variable(0.0, name="threshold") w_shape = int(X.get_shape()[1]), 1 # not shown in the book w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown b = tf.Variable(0.0, name="bias") # not shown z = tf.add(tf.matmul(X, w), b, name="z") # not shown return tf.maximum(z, relu.threshold, name="max") X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") relus = [relu(X) for i in range(5)] output = tf.add_n(relus, name="output") reset_graph() with tf.variable_scope("relu"): threshold = tf.get_variable("threshold", shape=(), initializer=tf.constant_initializer(0.0)) with tf.variable_scope("relu", reuse=True): threshold = tf.get_variable("threshold") with tf.variable_scope("relu") as scope: scope.reuse_variables() threshold = tf.get_variable("threshold") reset_graph() def relu(X): with tf.variable_scope("relu", reuse=True): threshold = tf.get_variable("threshold") w_shape = int(X.get_shape()[1]), 1 # not shown w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown b = tf.Variable(0.0, name="bias") # not shown z = tf.add(tf.matmul(X, w), b, name="z") # not shown return tf.maximum(z, threshold, name="max") X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") with tf.variable_scope("relu"): threshold = tf.get_variable("threshold", shape=(), initializer=tf.constant_initializer(0.0)) relus = [relu(X) for relu_index in range(5)] output = tf.add_n(relus, name="output") save_graph(run_id="relu6") %tensorboard --logdir {root_logdir} reset_graph() def relu(X): with tf.variable_scope("relu"): threshold = tf.get_variable("threshold", shape=(), initializer=tf.constant_initializer(0.0)) w_shape = (int(X.get_shape()[1]), 1) w = tf.Variable(tf.random_normal(w_shape), name="weights") b = tf.Variable(0.0, name="bias") z = tf.add(tf.matmul(X, w), b, name="z") return tf.maximum(z, threshold, name="max") X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") with tf.variable_scope("", default_name="") as scope: first_relu = relu(X) # create the shared variable scope.reuse_variables() # then reuse it relus = [first_relu] + [relu(X) for i in range(4)] output = tf.add_n(relus, name="output") save_graph(run_id="relu8") %tensorboard --logdir {root_logdir} reset_graph() def relu(X): threshold = tf.get_variable("threshold", shape=(), initializer=tf.constant_initializer(0.0)) w_shape = (int(X.get_shape()[1]), 1) # not shown in the book w = tf.Variable(tf.random_normal(w_shape), name="weights") # not shown b = tf.Variable(0.0, name="bias") # not shown z = tf.add(tf.matmul(X, w), b, name="z") # not shown return tf.maximum(z, threshold, name="max") X = tf.placeholder(tf.float32, shape=(None, n_features), name="X") relus = [] for relu_index in range(5): with tf.variable_scope("relu", reuse=(relu_index >= 1)) as scope: relus.append(relu(X)) output = tf.add_n(relus, name="output") save_graph(run_id="relu9") %tensorboard --logdir {root_logdir} """ Explanation: Sharing Variables Sharing a threshold variable the classic way, by defining it outside of the relu() function then passing it as a parameter: End of explanation """ reset_graph() with tf.variable_scope("my_scope"): x0 = tf.get_variable("x", shape=(), initializer=tf.constant_initializer(0.)) x1 = tf.Variable(0., name="x") x2 = tf.Variable(0., name="x") with tf.variable_scope("my_scope", reuse=True): x3 = tf.get_variable("x") x4 = tf.Variable(0., name="x") with tf.variable_scope("", default_name="", reuse=True): x5 = tf.get_variable("my_scope/x") print("x0:", x0.op.name) print("x1:", x1.op.name) print("x2:", x2.op.name) print("x3:", x3.op.name) print("x4:", x4.op.name) print("x5:", x5.op.name) print(x0 is x3 and x3 is x5) """ Explanation: Extra material End of explanation """ reset_graph() text = np.array("Do you want some café?".split()) text_tensor = tf.constant(text) with tf.Session() as sess: print(text_tensor.eval()) """ Explanation: The first variable_scope() block first creates the shared variable x0, named my_scope/x. For all operations other than shared variables (including non-shared variables), the variable scope acts like a regular name scope, which is why the two variables x1 and x2 have a name with a prefix my_scope/. Note however that TensorFlow makes their names unique by adding an index: my_scope/x_1 and my_scope/x_2. The second variable_scope() block reuses the shared variables in scope my_scope, which is why x0 is x3. Once again, for all operations other than shared variables it acts as a named scope, and since it's a separate block from the first one, the name of the scope is made unique by TensorFlow (my_scope_1) and thus the variable x4 is named my_scope_1/x. The third block shows another way to get a handle on the shared variable my_scope/x by creating a variable_scope() at the root scope (whose name is an empty string), then calling get_variable() with the full name of the shared variable (i.e. "my_scope/x"). Strings End of explanation """ from sklearn.datasets import make_moons m = 1000 X_moons, y_moons = make_moons(m, noise=0.1, random_state=42) """ Explanation: Autodiff Note: the autodiff content was moved to the extra_autodiff.ipynb notebook. Exercise solutions 1. to 11. See appendix A. 12. Logistic Regression with Mini-Batch Gradient Descent using TensorFlow First, let's create the moons dataset using Scikit-Learn's make_moons() function: End of explanation """ plt.plot(X_moons[y_moons == 1, 0], X_moons[y_moons == 1, 1], 'go', label="Positive") plt.plot(X_moons[y_moons == 0, 0], X_moons[y_moons == 0, 1], 'r^', label="Negative") plt.legend() plt.show() """ Explanation: Let's take a peek at the dataset: End of explanation """ X_moons_with_bias = np.c_[np.ones((m, 1)), X_moons] """ Explanation: We must not forget to add an extra bias feature ($x_0 = 1$) to every instance. For this, we just need to add a column full of 1s on the left of the input matrix $\mathbf{X}$: End of explanation """ X_moons_with_bias[:5] """ Explanation: Let's check: End of explanation """ y_moons_column_vector = y_moons.reshape(-1, 1) """ Explanation: Looks good. Now let's reshape y_train to make it a column vector (i.e. a 2D array with a single column): End of explanation """ test_ratio = 0.2 test_size = int(m * test_ratio) X_train = X_moons_with_bias[:-test_size] X_test = X_moons_with_bias[-test_size:] y_train = y_moons_column_vector[:-test_size] y_test = y_moons_column_vector[-test_size:] """ Explanation: Now let's split the data into a training set and a test set: End of explanation """ def random_batch(X_train, y_train, batch_size): rnd_indices = np.random.randint(0, len(X_train), batch_size) X_batch = X_train[rnd_indices] y_batch = y_train[rnd_indices] return X_batch, y_batch """ Explanation: Ok, now let's create a small function to generate training batches. In this implementation we will just pick random instances from the training set for each batch. This means that a single batch may contain the same instance multiple times, and also a single epoch may not cover all the training instances (in fact it will generally cover only about two thirds of the instances). However, in practice this is not an issue and it simplifies the code: End of explanation """ X_batch, y_batch = random_batch(X_train, y_train, 5) X_batch y_batch """ Explanation: Let's look at a small batch: End of explanation """ reset_graph() """ Explanation: Great! Now that the data is ready to be fed to the model, we need to build that model. Let's start with a simple implementation, then we will add all the bells and whistles. First let's reset the default graph. End of explanation """ n_inputs = 2 """ Explanation: The moons dataset has two input features, since each instance is a point on a plane (i.e., 2-Dimensional): End of explanation """ X = tf.placeholder(tf.float32, shape=(None, n_inputs + 1), name="X") y = tf.placeholder(tf.float32, shape=(None, 1), name="y") theta = tf.Variable(tf.random_uniform([n_inputs + 1, 1], -1.0, 1.0, seed=42), name="theta") logits = tf.matmul(X, theta, name="logits") y_proba = 1 / (1 + tf.exp(-logits)) """ Explanation: Now let's build the Logistic Regression model. As we saw in chapter 4, this model first computes a weighted sum of the inputs (just like the Linear Regression model), and then it applies the sigmoid function to the result, which gives us the estimated probability for the positive class: $\hat{p} = h_\boldsymbol{\theta}(\mathbf{x}) = \sigma(\boldsymbol{\theta}^T \mathbf{x})$ Recall that $\boldsymbol{\theta}$ is the parameter vector, containing the bias term $\theta_0$ and the weights $\theta_1, \theta_2, \dots, \theta_n$. The input vector $\mathbf{x}$ contains a constant term $x_0 = 1$, as well as all the input features $x_1, x_2, \dots, x_n$. Since we want to be able to make predictions for multiple instances at a time, we will use an input matrix $\mathbf{X}$ rather than a single input vector. The $i^{th}$ row will contain the transpose of the $i^{th}$ input vector $(\mathbf{x}^{(i)})^T$. It is then possible to estimate the probability that each instance belongs to the positive class using the following equation: $ \hat{\mathbf{p}} = \sigma(\mathbf{X} \boldsymbol{\theta})$ That's all we need to build the model: End of explanation """ y_proba = tf.sigmoid(logits) """ Explanation: In fact, TensorFlow has a nice function tf.sigmoid() that we can use to simplify the last line of the previous code: End of explanation """ epsilon = 1e-7 # to avoid an overflow when computing the log loss = -tf.reduce_mean(y * tf.log(y_proba + epsilon) + (1 - y) * tf.log(1 - y_proba + epsilon)) """ Explanation: As we saw in chapter 4, the log loss is a good cost function to use for Logistic Regression: $J(\boldsymbol{\theta}) = -\dfrac{1}{m} \sum\limits_{i=1}^{m}{\left[ y^{(i)} \log\left(\hat{p}^{(i)}\right) + (1 - y^{(i)}) \log\left(1 - \hat{p}^{(i)}\right)\right]}$ One option is to implement it ourselves: End of explanation """ loss = tf.losses.log_loss(y, y_proba) # uses epsilon = 1e-7 by default """ Explanation: But we might as well use TensorFlow's tf.losses.log_loss() function: End of explanation """ learning_rate = 0.01 optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(loss) """ Explanation: The rest is pretty standard: let's create the optimizer and tell it to minimize the cost function: End of explanation """ init = tf.global_variables_initializer() """ Explanation: All we need now (in this minimal version) is the variable initializer: End of explanation """ n_epochs = 1000 batch_size = 50 n_batches = int(np.ceil(m / batch_size)) with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): for batch_index in range(n_batches): X_batch, y_batch = random_batch(X_train, y_train, batch_size) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) loss_val = loss.eval({X: X_test, y: y_test}) if epoch % 100 == 0: print("Epoch:", epoch, "\tLoss:", loss_val) y_proba_val = y_proba.eval(feed_dict={X: X_test, y: y_test}) """ Explanation: And we are ready to train the model and use it for predictions! There's really nothing special about this code, it's virtually the same as the one we used earlier for Linear Regression: End of explanation """ y_proba_val[:5] """ Explanation: Note: we don't use the epoch number when generating batches, so we could just have a single for loop rather than 2 nested for loops, but it's convenient to think of training time in terms of number of epochs (i.e., roughly the number of times the algorithm went through the training set). For each instance in the test set, y_proba_val contains the estimated probability that it belongs to the positive class, according to the model. For example, here are the first 5 estimated probabilities: End of explanation """ y_pred = (y_proba_val >= 0.5) y_pred[:5] """ Explanation: To classify each instance, we can go for maximum likelihood: classify as positive any instance whose estimated probability is greater or equal to 0.5: End of explanation """ from sklearn.metrics import precision_score, recall_score precision_score(y_test, y_pred) recall_score(y_test, y_pred) """ Explanation: Depending on the use case, you may want to choose a different threshold than 0.5: make it higher if you want high precision (but lower recall), and make it lower if you want high recall (but lower precision). See chapter 3 for more details. Let's compute the model's precision and recall: End of explanation """ y_pred_idx = y_pred.reshape(-1) # a 1D array rather than a column vector plt.plot(X_test[y_pred_idx, 1], X_test[y_pred_idx, 2], 'go', label="Positive") plt.plot(X_test[~y_pred_idx, 1], X_test[~y_pred_idx, 2], 'r^', label="Negative") plt.legend() plt.show() """ Explanation: Let's plot these predictions to see what they look like: End of explanation """ X_train_enhanced = np.c_[X_train, np.square(X_train[:, 1]), np.square(X_train[:, 2]), X_train[:, 1] ** 3, X_train[:, 2] ** 3] X_test_enhanced = np.c_[X_test, np.square(X_test[:, 1]), np.square(X_test[:, 2]), X_test[:, 1] ** 3, X_test[:, 2] ** 3] """ Explanation: Well, that looks pretty bad, doesn't it? But let's not forget that the Logistic Regression model has a linear decision boundary, so this is actually close to the best we can do with this model (unless we add more features, as we will show in a second). Now let's start over, but this time we will add all the bells and whistles, as listed in the exercise: * Define the graph within a logistic_regression() function that can be reused easily. * Save checkpoints using a Saver at regular intervals during training, and save the final model at the end of training. * Restore the last checkpoint upon startup if training was interrupted. * Define the graph using nice scopes so the graph looks good in TensorBoard. * Add summaries to visualize the learning curves in TensorBoard. * Try tweaking some hyperparameters such as the learning rate or the mini-batch size and look at the shape of the learning curve. Before we start, we will add 4 more features to the inputs: ${x_1}^2$, ${x_2}^2$, ${x_1}^3$ and ${x_2}^3$. This was not part of the exercise, but it will demonstrate how adding features can improve the model. We will do this manually, but you could also add them using sklearn.preprocessing.PolynomialFeatures. End of explanation """ X_train_enhanced[:5] """ Explanation: This is what the "enhanced" training set looks like: End of explanation """ reset_graph() """ Explanation: Ok, next let's reset the default graph: End of explanation """ def logistic_regression(X, y, initializer=None, seed=42, learning_rate=0.01): n_inputs_including_bias = int(X.get_shape()[1]) with tf.name_scope("logistic_regression"): with tf.name_scope("model"): if initializer is None: initializer = tf.random_uniform([n_inputs_including_bias, 1], -1.0, 1.0, seed=seed) theta = tf.Variable(initializer, name="theta") logits = tf.matmul(X, theta, name="logits") y_proba = tf.sigmoid(logits) with tf.name_scope("train"): loss = tf.losses.log_loss(y, y_proba, scope="loss") optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) training_op = optimizer.minimize(loss) loss_summary = tf.summary.scalar('log_loss', loss) with tf.name_scope("init"): init = tf.global_variables_initializer() with tf.name_scope("save"): saver = tf.train.Saver() return y_proba, loss, training_op, loss_summary, init, saver """ Explanation: Now let's define the logistic_regression() function to create the graph. We will leave out the definition of the inputs X and the targets y. We could include them here, but leaving them out will make it easier to use this function in a wide range of use cases (e.g. perhaps we will want to add some preprocessing steps for the inputs before we feed them to the Logistic Regression model). End of explanation """ from datetime import datetime def log_dir(prefix=""): now = datetime.utcnow().strftime("%Y%m%d%H%M%S") root_logdir = "tf_logs" if prefix: prefix += "-" name = prefix + "run-" + now return "{}/{}/".format(root_logdir, name) """ Explanation: Let's create a little function to get the name of the log directory to save the summaries for Tensorboard: End of explanation """ n_inputs = 2 + 4 logdir = log_dir("logreg") X = tf.placeholder(tf.float32, shape=(None, n_inputs + 1), name="X") y = tf.placeholder(tf.float32, shape=(None, 1), name="y") y_proba, loss, training_op, loss_summary, init, saver = logistic_regression(X, y) file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph()) """ Explanation: Next, let's create the graph, using the logistic_regression() function. We will also create the FileWriter to save the summaries to the log directory for Tensorboard: End of explanation """ n_epochs = 10001 batch_size = 50 n_batches = int(np.ceil(m / batch_size)) checkpoint_path = "/tmp/my_logreg_model.ckpt" checkpoint_epoch_path = checkpoint_path + ".epoch" final_model_path = "./my_logreg_model" with tf.Session() as sess: if os.path.isfile(checkpoint_epoch_path): # if the checkpoint file exists, restore the model and load the epoch number with open(checkpoint_epoch_path, "rb") as f: start_epoch = int(f.read()) print("Training was interrupted. Continuing at epoch", start_epoch) saver.restore(sess, checkpoint_path) else: start_epoch = 0 sess.run(init) for epoch in range(start_epoch, n_epochs): for batch_index in range(n_batches): X_batch, y_batch = random_batch(X_train_enhanced, y_train, batch_size) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) loss_val, summary_str = sess.run([loss, loss_summary], feed_dict={X: X_test_enhanced, y: y_test}) file_writer.add_summary(summary_str, epoch) if epoch % 500 == 0: print("Epoch:", epoch, "\tLoss:", loss_val) saver.save(sess, checkpoint_path) with open(checkpoint_epoch_path, "wb") as f: f.write(b"%d" % (epoch + 1)) saver.save(sess, final_model_path) y_proba_val = y_proba.eval(feed_dict={X: X_test_enhanced, y: y_test}) os.remove(checkpoint_epoch_path) file_writer.close() """ Explanation: At last we can train the model! We will start by checking whether a previous training session was interrupted, and if so we will load the checkpoint and continue training from the epoch number we saved. In this example we just save the epoch number to a separate file, but in chapter 11 we will see how to store the training step directly as part of the model, using a non-trainable variable called global_step that we pass to the optimizer's minimize() method. You can try interrupting training to verify that it does indeed restore the last checkpoint when you start it again. End of explanation """ y_pred = (y_proba_val >= 0.5) precision_score(y_test, y_pred) recall_score(y_test, y_pred) y_pred_idx = y_pred.reshape(-1) # a 1D array rather than a column vector plt.plot(X_test[y_pred_idx, 1], X_test[y_pred_idx, 2], 'go', label="Positive") plt.plot(X_test[~y_pred_idx, 1], X_test[~y_pred_idx, 2], 'r^', label="Negative") plt.legend() plt.show() """ Explanation: Once again, we can make predictions by just classifying as positive all the instances whose estimated probability is greater or equal to 0.5: End of explanation """ %tensorboard --logdir {root_logdir} """ Explanation: Now that's much, much better! Apparently the new features really helped a lot. Let's open tensorboard, find the latest run and look at the learning curve: End of explanation """ from scipy.stats import reciprocal n_search_iterations = 10 for search_iteration in range(n_search_iterations): batch_size = np.random.randint(1, 100) learning_rate = reciprocal(0.0001, 0.1).rvs(random_state=search_iteration) n_inputs = 2 + 4 logdir = log_dir("logreg") print("Iteration", search_iteration) print(" logdir:", logdir) print(" batch size:", batch_size) print(" learning_rate:", learning_rate) print(" training: ", end="") reset_graph() X = tf.placeholder(tf.float32, shape=(None, n_inputs + 1), name="X") y = tf.placeholder(tf.float32, shape=(None, 1), name="y") y_proba, loss, training_op, loss_summary, init, saver = logistic_regression( X, y, learning_rate=learning_rate) file_writer = tf.summary.FileWriter(logdir, tf.get_default_graph()) n_epochs = 10001 n_batches = int(np.ceil(m / batch_size)) final_model_path = "./my_logreg_model_%d" % search_iteration with tf.Session() as sess: sess.run(init) for epoch in range(n_epochs): for batch_index in range(n_batches): X_batch, y_batch = random_batch(X_train_enhanced, y_train, batch_size) sess.run(training_op, feed_dict={X: X_batch, y: y_batch}) loss_val, summary_str = sess.run([loss, loss_summary], feed_dict={X: X_test_enhanced, y: y_test}) file_writer.add_summary(summary_str, epoch) if epoch % 500 == 0: print(".", end="") saver.save(sess, final_model_path) print() y_proba_val = y_proba.eval(feed_dict={X: X_test_enhanced, y: y_test}) y_pred = (y_proba_val >= 0.5) print(" precision:", precision_score(y_test, y_pred)) print(" recall:", recall_score(y_test, y_pred)) file_writer.close() """ Explanation: Now you can play around with the hyperparameters (e.g. the batch_size or the learning_rate) and run training again and again, comparing the learning curves. You can even automate this process by implementing grid search or randomized search. Below is a simple implementation of a randomized search on both the batch size and the learning rate. For the sake of simplicity, the checkpoint mechanism was removed. End of explanation """
GoogleCloudPlatform/vertex-ai-samples
notebooks/community/ml_ops/stage4/get_started_with_vertex_ml_metadata.ipynb
apache-2.0
import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_WORKBENCH_NOTEBOOK: USER_FLAG = "--user" ! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG -q ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG -q """ Explanation: E2E ML on GCP: MLOps stage 4 : formalization: get started with Vertex AI ML Metadata <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage4/get_started_with_vertex_ml_metadata.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage4/get_started_with_vertex_ml_metadata.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> <td> <a href="https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/main/notebooks/community/ml_ops/stage4/get_started_with_vertex_ml_metadata.ipynb"> <img src="https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32" alt="Vertex AI logo"> Open in Vertex AI Workbench </a> </td> </table> <br/><br/><br/> Overview This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 4 : formalization: get started with Vertex AI ML Metadata. Dataset The dataset used for this tutorial is the UCI Machine Learning 'Dry beans dataset', from: KOKLU, M. and OZKAN, I.A., (2020), "Multiclass Classification of Dry Beans Using Computer Vision and Machine Learning Techniques."In Computers and Electronics in Agriculture, 174, 105507. DOI. Objective In this tutorial, you learn how to use Vertex AI ML Metadata. This tutorial uses the following Google Cloud ML services: Vertex AI ML Metadata Vertex AI Pipelines The steps performed include: Create a Metadatastore resource. Create (record)/List an Artifact, with artifacts and metadata. Create (record)/List an Execution. Create (record)/List a Context. Add Artifact to Execution as events. Add Execution and Artifact into the Context Delete Artifact, Execution and Context. Create and run a Vertex AI Pipeline ML workflow to train and deploy a scikit-learn model. Create custom pipeline components that generate artifacts and metadata. Compare Vertex AI Pipelines runs. Trace the lineage for pipeline-generated artifacts. Query your pipeline run metadata. Installations Install the packages required for executing the notebook. End of explanation """ import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) """ Explanation: Restart the kernel Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages. End of explanation """ PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = ! gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:", PROJECT_ID) ! gcloud config set project $PROJECT_ID """ Explanation: Before you begin GPU runtime Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the following APIs: Vertex AI APIs, Compute Engine APIs, and Cloud Storage. If you are running this notebook locally, you will need to install the Cloud SDK. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $. Set your project ID If you don't know your project ID, you may be able to get your project ID using gcloud. End of explanation """ REGION = "[your-region]" # @param {type: "string"} if REGION == "[your-region]": REGION = "us-central1" """ Explanation: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services. Learn more about Vertex AI regions. End of explanation """ from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") """ Explanation: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append the timestamp onto the name of resources you create in this tutorial. End of explanation """ # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. import os import sys # If on Vertex AI Workbench, then don't execute this code IS_COLAB = False if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv( "DL_ANACONDA_HOME" ): if "google.colab" in sys.modules: IS_COLAB = True from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): %env GOOGLE_APPLICATION_CREDENTIALS '' """ Explanation: Authenticate your Google Cloud account If you are using Vertex AI Workbench Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, go to the Create service account key page. Click Create service account. In the Service account name field, enter a name, and click Create. In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex" into the filter box, and select Vertex Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin. Click Create. A JSON file that contains your key downloads to your local environment. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. End of explanation """ BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"} BUCKET_URI = f"gs://{BUCKET_NAME}" if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]": BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP BUCKET_URI = "gs://" + BUCKET_NAME """ Explanation: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions. Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. End of explanation """ ! gsutil mb -l $REGION $BUCKET_URI """ Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket. End of explanation """ ! gsutil ls -al $BUCKET_URI """ Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents: End of explanation """ SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"} if ( SERVICE_ACCOUNT == "" or SERVICE_ACCOUNT is None or SERVICE_ACCOUNT == "[your-service-account]" ): # Get your service account from gcloud if not IS_COLAB: shell_output = !gcloud auth list 2>/dev/null SERVICE_ACCOUNT = shell_output[2].replace("*", "").strip() if IS_COLAB: shell_output = ! gcloud projects describe $PROJECT_ID project_number = shell_output[-1].split(":")[1].strip().replace("'", "") SERVICE_ACCOUNT = f"{project_number}-compute@developer.gserviceaccount.com" print("Service Account:", SERVICE_ACCOUNT) """ Explanation: Service Account If you don't know your service account, try to get your service account using gcloud command by executing the second cell below. End of explanation """ ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_URI ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_URI """ Explanation: Set service account access for Vertex AI Pipelines Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account. End of explanation """ import google.cloud.aiplatform as aip """ Explanation: Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants End of explanation """ import google.cloud.aiplatform_v1beta1 as aip_beta """ Explanation: Import Vertex AI SDK Import the Vertex AI SDK into your Python environment. End of explanation """ # API service endpoint API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION) # Vertex location root path for your dataset, model and endpoint resources PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION """ Explanation: Vertex AI constants Setup up the following constants for Vertex AI: API_ENDPOINT: The Vertex AI API service endpoint for ML Metadata services. End of explanation """ # client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_metadata_client(): client = aip_beta.MetadataServiceClient(client_options=client_options) return client clients = {} clients["metadata"] = create_metadata_client() for client in clients.items(): print(client) """ Explanation: Set up clients The Vertex works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the Vertex AI server. You will use different clients in this tutorial for different steps in the workflow. So set them all up upfront. Metadata Service for creating recording, searching and analyzing artifacts and metadata. End of explanation """ metadata_store = clients["metadata"].create_metadata_store( parent=PARENT, metadata_store_id="my-metadata-store" ) metadata_store_id = str(metadata_store.result())[7:-2] print(metadata_store_id) """ Explanation: Introduction to Vertex AI Metadata The Vertex AI ML Metadata service provides you with the ability to record, and subsequently search and analyze, the artifacts and corresponding metadata produced by your ML workflows. For example, during experimentation one might desire to record the location of the model artifacts, as artifacts, and the training hyperparameters and evaluation metrics as the corresponding metadata. The service supports recording ML metadata both manually and automatically, with the later occurring when you use Vertex AI Pipelines. Concepts and organization Vertex ML Metadata describes your ML system's metadata as a graph. Artifacts: Artifacts are pieces of data that ML systems consume or produce, such as: datasets, models, or logs. For large artifacts like datasets or models, the artifact record includes the URI where the data is stored. Executions: Executions describe a single step in your ML system's workflow. Events: Executions can depend on artifacts as inputs or produce artifacts as outputs. Events describe the relationship between artifacts and executions to help you determine the lineage of artifacts. For example, an event is created to record that a dataset is used by an execution, and another event is created to record that this execution produced a model. Contexts: Contexts let you group artifacts and executions together in a single, queryable, and typed category. ML artifact lineage Vertex AI ML Metadata provides the ability to understand changes in the performance of your machine ML system, and analyze the metadata produced by your ML workflow and the lineage of its artifacts. An artifact's lineage includes all the factors that contributed to its creation, as well as artifacts and metadata that descend from this artifact. Learn more about Introduction to Vertex AI ML Metadata Create a MetadataStore resource Each project may have one or more MetadataStore resources. By default, if none is explicity created, each project has a default, which is specified as: projects/&lt;project_id&gt;/locations/&lt;region&gt;/metadataStores/&lt;name&gt; You create a MetadataStore resource using the create_metadata_store() method, with the following parameters: parent: The fully qualified subpath for all resources in your project, i.e., projects/<project_id>/locations/<location> metadata_store_id: The name of the MetadataStore resource. End of explanation """ schemas = clients["metadata"].list_metadata_schemas(parent=metadata_store_id) for schema in schemas: print(schema) """ Explanation: List metadata schemas When you create an Artifact, Execution or Context resource, you specify a schema that describes the corresponding metadata. The schemas must be pre-registered for your Metadatastore resource. You can get a list of all registered schemas, default and user defined, using the list_metadata_schemas() method, with the following parameters: name: The fully qualified resource identifier for the MetadataStore resource. Learn more about Metadata system schemas. End of explanation """ from google.cloud.aiplatform_v1beta1.types import Artifact artifact_item = Artifact( display_name="my_example_artifact", uri="my_url", labels={"my_label": "value"}, schema_title="system.Artifact", metadata={"param": "value"}, ) artifact = clients["metadata"].create_artifact( parent=metadata_store_id, artifact=artifact_item, artifact_id="myartifactid", ) print(artifact) """ Explanation: Create an Artifact resource You create an Artifact resource using the create_artifact() method, with the following parameters: parent: The fully qualified resource identifier to the Metadatastore resource. artifact: The definition of the Artifact resource display_name: The human readable name for the Artifact resource. uri: The uniform resource identifier of the artifact file. May be empty if there is no actual artifact file. labels: User defined labels to assign to the Artifact resource. schema_title: The title of the schema that describes the metadata. metadata: The metadata key/value pairs to associate with the Artifact resource. artifact_id: (optional) A user defined short ID for the Artifact resource. End of explanation """ artifacts = clients["metadata"].list_artifacts(parent=metadata_store_id) for _artifact in artifacts: print(_artifact) """ Explanation: List Artifact resources in a Metadatastore You can list all Artifact resources using the list_artifacts() method, with the following parameters: parent: The fully qualified resource identifier for the MetadataStore resource. End of explanation """ from google.cloud.aiplatform_v1beta1.types import Execution execution = clients["metadata"].create_execution( parent=metadata_store_id, execution=Execution( display_name="my_execution", schema_title="system.CustomJobExecution", metadata={"value": "param"}, ), execution_id="myexecutionid", ) print(execution) """ Explanation: Create an Execution resource You create an Execution resource using the create_execution() method, with the following parameters: parent: The fully qualified resource identifier to the Metadatastore resource. execution: display_name: A human readable name for the Execution resource. schema_title: The title of the schema that describes the metadata. metadata: The metadata key/value pairs to associate with the Execution resource. execution_id: (optional) A user defined short ID for the Execution resource. End of explanation """ executions = clients["metadata"].list_executions(parent=metadata_store_id) for _execution in executions: print(_execution) """ Explanation: List Execution resources in a Metadatastore You can list all Execution resources using the list_executions() method, with the following parameters: parent: The fully qualified resource identifier for the MetadataStore resource. End of explanation """ from google.cloud.aiplatform_v1beta1.types import Context context = clients["metadata"].create_context( parent=metadata_store_id, context=Context( display_name="my_context", labels=[{"my_label", "my_value"}], schema_title="system.Pipeline", metadata={"param": "value"}, ), context_id="mycontextid", ) print(context) """ Explanation: Create a Context resource You create an Context resource using the create_context() method, with the following parameters: parent: The fully qualified resource identifier to the Metadatastore resource. context: display_name: A human readable name for the Execution resource. schema_title: The title of the schema that describes the metadata. labels: User defined labels to assign to the Context resource. metadata: The metadata key/value pairs to associate with the Execution resource. context_id: (optional) A user defined short ID for the Context resource. End of explanation """ contexts = clients["metadata"].list_contexts(parent=metadata_store_id) for _context in contexts: print(_context) """ Explanation: List Context resources in a Metadatastore You can list all Context resources using the list_contexts() method, with the following parameters: parent: The fully qualified resource identifier for the MetadataStore resource. End of explanation """ from google.cloud.aiplatform_v1beta1.types import Event clients["metadata"].add_execution_events( execution=execution.name, events=[ Event( artifact=artifact.name, type_=Event.Type.INPUT, labels={"my_label": "my_value"}, ) ], ) """ Explanation: Add events to Execution resource An Execution resource consists of a sequence of events that occurred during the execution. Each event consists of an artifact that is either an input or an output of the Execution resource. You can add execution events to an Execution resource using the add_execution_events() method, with the following parameters: execution: The fully qualified resource identifier for the Execution resource. events: The sequence of events constituting the execution. End of explanation """ clients["metadata"].add_context_artifacts_and_executions( context=context.name, artifacts=[artifact.name], executions=[execution.name] ) """ Explanation: Combine Artifacts and Executions into a Context A Context is used to group Artifact resources and Execution resources together under a single, queryable, and typed category. Contexts can be used to represent sets of metadata. You can combine a set of Artifact and Execution resources into a Context resource using the add_context_artifacts_and_executions() method, with the following parameters: context: The fully qualified resource identifier of the Context resource. artifacts: A list of fully qualified resource identifiers of the Artifact resources. executions: A list of fully qualified resource identifiers of the Execution resources. End of explanation """ subgraph = clients["metadata"].query_context_lineage_subgraph(context=context.name) print(subgraph) """ Explanation: Query a context You can query the subgraph of a Context resource using the method query_context_lineage_subgraph() method, with the following parameters: context: The fully qualified resource identifier of the Context resource. End of explanation """ clients["metadata"].delete_artifact(name=artifact.name) """ Explanation: Delete an Artifact resource You can delete an Artifact resource using the delete_artifact() method, with the following parameters: name: The fully qualified resource identifier for the Artifact resource. End of explanation """ clients["metadata"].delete_execution(name=execution.name) """ Explanation: Delete an Execution resource You can delete an Execution resource using the delete_execution() method, with the following parameters: name: The fully qualified resource identifier for the Execution resource. End of explanation """ clients["metadata"].delete_context(name=context.name) """ Explanation: Delete a Context resource You can delete an Context resource using the delete_context() method, with the following parameters: name: The fully qualified resource identifier for the Context resource. End of explanation """ from kfp.v2 import compiler, dsl from kfp.v2.dsl import (Artifact, Dataset, Input, Metrics, Model, Output, OutputPath, component, pipeline) """ Explanation: Introduction to tracking ML Metadata in a Vertex AI Pipeline Vertex AI Pipelines automatically records the metrics and artifacts created when the pipeline is exeuted. You can then use the SDK to track and analyze the metrics and artifacts across pipeline runs. End of explanation """ @component( packages_to_install=["google-cloud-bigquery", "pandas", "pyarrow"], base_image="python:3.9", output_component_file="create_dataset.yaml", ) def get_dataframe(bq_table: str, output_data_path: OutputPath("Dataset")): from google.cloud import bigquery bqclient = bigquery.Client() table = bigquery.TableReference.from_string(bq_table) rows = bqclient.list_rows(table) dataframe = rows.to_dataframe( create_bqstorage_client=True, ) dataframe = dataframe.sample(frac=1, random_state=2) dataframe.to_csv(output_data_path) @component( packages_to_install=["sklearn", "pandas", "joblib"], base_image="python:3.9", output_component_file="beans_model_component.yaml", ) def sklearn_train( dataset: Input[Dataset], metrics: Output[Metrics], model: Output[Model] ): import pandas as pd from joblib import dump from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier df = pd.read_csv(dataset.path) labels = df.pop("Class").tolist() data = df.values.tolist() x_train, x_test, y_train, y_test = train_test_split(data, labels) skmodel = DecisionTreeClassifier() skmodel.fit(x_train, y_train) score = skmodel.score(x_test, y_test) print("accuracy is:", score) metrics.log_metric("accuracy", (score * 100.0)) metrics.log_metric("framework", "Scikit Learn") metrics.log_metric("dataset_size", len(df)) dump(skmodel, model.path + ".joblib") @component( packages_to_install=["google-cloud-aiplatform"], base_image="python:3.9", output_component_file="beans_deploy_component.yaml", ) def deploy_model( model: Input[Model], project: str, region: str, vertex_endpoint: Output[Artifact], vertex_model: Output[Model], ): from google.cloud import aiplatform aiplatform.init(project=project, location=region) deployed_model = aiplatform.Model.upload( display_name="beans-model-pipeline", artifact_uri=model.uri.replace("model", ""), serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.0-24:latest", ) endpoint = deployed_model.deploy(machine_type="n1-standard-4") # Save data to the output params vertex_endpoint.uri = endpoint.resource_name vertex_model.uri = deployed_model.resource_name """ Explanation: Creating a 3-step pipeline with custom components First, you create a pipeline to run on Vertex AI Pipelines, consisting of the following custom components: get_dataframe: Retrieve data from a BigQuery table and convert it into a pandas DataFrame. sklearn_train: Use the pandas DataFrame to train and export a scikit-learn model, along with some metrics. deploy_model: Deploy the exported scikit-learn model to a Vertex AI Endpoint resource. get_dataframe component This component does the following: Creates a reference to a BigQuery table using the BigQuery client library Downloads the BigQuery table and converts it to a shuffled pandas DataFrame Exports the DataFrame to a CSV file sklearn_train component This component does the following: Imports a CSV as a pandas DataFrame Splits the DataFrame into train and test sets Trains a scikit-learn model Logs metrics from the model Saves the model artifacts as a local model.joblib file deploy_model component This component does the following: Uploads the scikit-learn model to a Vertex AI Model resource. Deploys the model to a Vertex AI Endpoint resource. End of explanation """ PIPELINE_ROOT = f"{BUCKET_URI}/pipeline_root/3step" @dsl.pipeline( # Default pipeline root. You can override it when submitting the pipeline. pipeline_root=PIPELINE_ROOT, # A name for the pipeline. name="mlmd-pipeline", ) def pipeline( bq_table: str = "", output_data_path: str = "data.csv", project: str = PROJECT_ID, region: str = REGION, ): dataset_task = get_dataframe(bq_table) model_task = sklearn_train(dataset_task.output) deploy_model(model=model_task.outputs["model"], project=project, region=region) """ Explanation: Construct and compile the pipeline Next, construct the pipeline: End of explanation """ NOW = datetime.now().isoformat().replace(".", ":")[:-7] compiler.Compiler().compile(pipeline_func=pipeline, package_path="mlmd_pipeline.json") run1 = aip.PipelineJob( display_name="mlmd-pipeline", template_path="mlmd_pipeline.json", job_id="mlmd-pipeline-small-{}".format(TIMESTAMP), parameter_values={"bq_table": "sara-vertex-demos.beans_demo.small_dataset"}, enable_caching=True, ) run2 = aip.PipelineJob( display_name="mlmd-pipeline", template_path="mlmd_pipeline.json", job_id="mlmd-pipeline-large-{}".format(TIMESTAMP), parameter_values={"bq_table": "sara-vertex-demos.beans_demo.large_dataset"}, enable_caching=True, ) run1.run() run2.run() run1.delete() run2.delete() ! rm -f mlmd_pipeline.json *.yaml """ Explanation: Compile and execute two runs of the pipeline Next, you compile the pipeline and then run two separate instances of the pipeline. In the first instance, you train the model with a small version of the dataset and in the second instance you train it with a larger version of the dataset. End of explanation """ df = aip.get_pipeline_df(pipeline="mlmd-pipeline") print(df) """ Explanation: Compare the pipeline runs Now that you have two pipeline completed pipeline runs, you can compare the runs. You can use the get_pipeline_df() method to access the metadata from the runs. The mlmd-pipeline parameter here refers to the name you gave to your pipeline: Alternately, for guidance on inspecting pipeline artifacts and metadata in the Vertex AI Console, see this codelab. End of explanation """ import matplotlib.pyplot as plt plt.plot(df["metric.dataset_size"], df["metric.accuracy"], label="Accuracy") plt.title("Accuracy and dataset size") plt.legend(loc=4) plt.show() """ Explanation: Visualize the pipeline runs Next, you create a custom visualization with matplotlib to see the relationship between your model's accuracy and the amount of data used for training. End of explanation """ FILTER = f'create_time >= "{NOW}" AND state = LIVE' artifact_req = { "parent": metadata_store_id, "filter": FILTER, } artifacts = clients["metadata"].list_artifacts(artifact_req) for _artifact in artifacts: print(_artifact) clients["metadata"].delete_artifact(name=_artifact.name) """ Explanation: Quering your Metadatastore resource Finally, you query your Metadatastore resource by specifying a filter parameter when calling the list_artifacts() method. End of explanation """ clients["metadata"].delete_metadata_store(name=metadata_store_id) """ Explanation: Delete a MetadataStore resource You can delete a MetadataStore resource using the delete_metadata_store() method, with the following parameters: name: The fully qualified resource identifier for the MetadataStore resource. End of explanation """ delete_bucket = False if delete_bucket or os.getenv("IS_TESTING"): ! gsutil rm -r $BUCKET_URI """ Explanation: Cleaning up To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial. End of explanation """
pastas/pastas
concepts/response_functions.ipynb
mit
import numpy as np import pandas as pd import pastas as ps import matplotlib.pyplot as plt ps.show_versions() """ Explanation: Response functions This notebook provides an overview of the response functions that are available in Pastas. Response functions describe the response of the dependent variable (e.g., groundwater levels) to an independent variable (e.g., groundwater pumping) and form a fundamental part in the transfer function noise models implemented in Pastas. Depending on the problem under investigation, a less or more complex response function may be required, where the complexity is quantified by the number of parameters. Response function are generally used in combination with a stressmodel, but in this notebook the response functions are studied independently to provide an overview of the different response functions and what they represent. End of explanation """ # Default Settings cutoff = 0.999 meanstress = 1 up = True responses = {} exp = ps.Exponential(up=up, meanstress=meanstress, cutoff=cutoff) responses["Exponential"] = exp gamma = ps.Gamma(up=up, meanstress=meanstress, cutoff=cutoff) responses["Gamma"] = gamma hantush = ps.Hantush(up=up, meanstress=meanstress, cutoff=cutoff) responses["Hantush"] = hantush polder = ps.Polder(up=up, meanstress=meanstress, cutoff=cutoff) responses["Polder"] = polder fourp = ps.FourParam(up=up, meanstress=meanstress, cutoff=cutoff) responses["FourParam"] = fourp DoubleExp = ps.DoubleExponential(up=up, meanstress=meanstress, cutoff=cutoff) responses["DoubleExponential"] = DoubleExp parameters = pd.DataFrame() fig, [ax1, ax2] = plt.subplots(1,2, sharex=True, figsize=(10,3)) for name, response in responses.items(): p = response.get_init_parameters(name) parameters = parameters.append(p) ax1.plot(response.block(p.initial), label=name) ax2.plot(response.step(p.initial), label=name) ax1.set_title("Block response") ax2.set_title("Step responses") ax1.set_xlabel("Time [days]") ax2.set_xlabel("Time [days]") ax1.legend() plt.xlim(1e-1, 500) plt.show() """ Explanation: The use of response functions Depending on the stress type (e.g., recharge, river levels or groundwater pumping) different response function may be used. All response functions that are tested and supported in Pastas are summarized in the table below for reference. The equation in the third column is the formula for the impulse response function ($\theta(t)$). |Name|Parameters|Formula|Description| |----|----------|:------|-----------| | FourParam |4 - A, n, a, b| $$ \theta(t) = A \frac{t^{n-1}}{a^n \Gamma(n)} e^{-t/a- ab/t} $$ | Response function with four parameters that may be used for many purposes. Many other response function are a simplification of this function. | | Gamma |3 - A, a, n | $$ \theta(t) = A \frac{t^{n-1}}{a^n \Gamma(n)} e^{-t/a} $$ | Three parameter version of FourParam, used for all sorts of stresses ($b=0$) | | Exponential |2 - A, a | $$ \theta(t) = \frac{A}{a} e^{-t/a} $$ | Response function that can be used for stresses that have an (almost) instant effect. ($n=1$ and $b=0$)| | Hantush |3 - A, a, b | $$ \theta(t) = A\frac{t^{-1}}{2\text{K}_0(2\sqrt{b})} e^{-t/a - ab/t} $$ | Response function commonly used for groundwater extraction wells ($n=0$) | | Polder |3 - a, b, c | $$ \theta(t) = At^{-3/2} e^{-t/a -b/t} $$ | Response function commonly used to simulate the effects of (river) water levels on the groundwater levels ($n=-1/2$) | | DoubleExponential |4 - A, $\alpha$, $a_1$,$a_2$| $$ \theta(t) = A (1 - \alpha) e^{-t/a_1} + A \alpha e^{-t/a_2} $$ | Response Function with a double exponential, simulating a fast and slow response. | | Edelman | 1 - $\beta$ | $$ \theta(t) = \text{?} $$ | The function of Edelman, describing the propagation of an instantaneous water level change into an adjacent half-infinite aquifer. | | HantushWellModel | 3 - A, a, b| $$ \theta(t) = \text{?} $$ | A special implementation of the Hantush well function for multiple wells. | Below the different response functions are plotted. End of explanation """ A = 1 a = 50 b = 0.4 plt.figure(figsize=(16, 8)) for i, n in enumerate([-0.5, 1e-6, 0.5, 1, 1.5]): plt.subplot(2, 3, i + 1) plt.title(f'n={n:0.1f}') fp = fourp.step([A, n, a, b], dt=1, cutoff=0.95) plt.plot(np.arange(1, len(fp) + 1), fp, 'C0', label='4-param') e = exp.step([A, a], dt=1, cutoff=0.95) plt.plot(np.arange(1, len(e) + 1), e, 'C1', label='exp') if n > 0: g = gamma.step([A, n, a], dt=1, cutoff=0.95) plt.plot(np.arange(1, len(g) + 1), g, 'C2', label='gamma') h = hantush.step([A, a, b], dt=1, cutoff=0.95) / hantush.gain([A, a, b]) plt.plot(np.arange(1, len(h) + 1), h, 'C3', label='hantush') p = polder.step([A, a, b], dt=1, cutoff=0.95) / polder.gain([A, a, b]) plt.plot(np.arange(1, len(p) + 1), p, 'C4', label='polder') plt.xlim(0, 200) plt.legend() if n > 0: print('fp, e, g, h, p:', fp[-1], e[-1], g[-1], h[-1], p[-1]) else: print('fp, e, h, p:', fp[-1], e[-1], h[-1], p[-1]) plt.axhline(0.95, linestyle=':') """ Explanation: Scaling of the step response functions An important characteristic is the so-called "gain" of a response function. The gain is the final increase or decrease that results from a unit increase or decrease in a stress that continues infinitely in time (e.g., pumping at a constant rate forever). This can be visually inspected by the value of the step response function for large values of $t$ but can also be inferred from the parameters as follows: The FourParam, Gamma, Exponential, and Hantush step functions are scaled such that the gain equals $A$ The Polder function is scaled such that the gain equals $\exp\left(-2\sqrt{b}\right)$ The gain of the Edelman function always equals 1, but this will take an infinite amount of time. Comparison of the different response functions The Gamma, Exponential, Polder, and Hantush response function can all be derived from the more general FourParam response function by fixing the parameters $n$ and/or $b$ to a specific value. The DoubleExponential, Edelman, and HantushWellModel cannot be written as some form of the FourParam function. Below the response function that are special forms of the four parameter function are are shown for different values of $n$ and $b$. End of explanation """ parameters """ Explanation: Parameter settings up : This parameters determines whether the influence of the stress goes up or down, hence a positive or a negative response function. For example, when groundwater pumping is defined as a positive flux, up=False because we want the groundwater levels to decrease as a result of pumping. meanstress : This parameter is used to estimate the initial value of the stationary effect of a stress. Hence the effect when a stress stays at an unit level for infinite amount of time. This parameter is usually referred from the stress time series and does not have to be provided by the user. cutoff : This parameter determines for how many time steps the response is calculated. This reduces calculation times as it reduces the length of the array the stress is convolved with. The default value is 0.999, meaning that the response is cutoff after 99.9% of the effect of the stress impulse has occurred. A minimum of length of three times the simulation time step is applied. The default parameter values for each of the response function are as follows: End of explanation """ from scipy.special import erfc def polder_classic(t, x, T, S, c): X = x / (2 * np.sqrt(T * c)) Y = np.sqrt(t / (c * S)) rv = 0.5 * np.exp(2 * X) * erfc(X / Y + Y) + \ 0.5 * np.exp(-2 * X) * erfc(X / Y - Y) return rv delh = 2 T = 20 c = 5000 S = 0.01 x = 400 x / np.sqrt(c * T) t = np.arange(1, 121) h_polder_classic = np.zeros(len(t)) for i in range(len(t)): h_polder_classic[i] = delh * polder_classic(t[i], x=x, T=T, S=S, c=c) # A = delh a = c * S b = x ** 2 / (4 * T * c) pd = polder.step([A, a, b], dt=1, cutoff=0.95) # plt.plot(t, h_polder_classic, label='Polder classic') plt.plot(np.arange(1, len(pd) + 1), pd, label='Polder Pastas', linestyle="--") plt.legend() """ Explanation: Comparison to classical analytical response functions Polder step function compared to classic polder function The classic polder function is (Eq. 123.32 in Bruggeman, 1999) $$ h(t) = \Delta h \text{P}\left(\frac{x}{2\lambda}, \sqrt{\frac{t}{cS}}\right) $$ where P is the polder function. End of explanation """ from scipy.integrate import quad from scipy.special import k0 def integrand_hantush(y, r, lab): return np.exp(-y - r ** 2 / (4 * lab ** 2 * y)) / y def hantush_classic(t=1, r=1, Q=1, T=100, S=1e-4, c=1000): lab = np.sqrt(T * c) u = r ** 2 * S / (4 * T * t) F = quad(integrand_hantush, u, np.inf, args=(r, lab))[0] return -Q / (4 * np.pi * T) * F c = 1000 # d S = 0.01 # - T = 100 # m^2/d r = 500 # m Q = 20 # m^3/d lab = np.sqrt(T * c) # t = np.arange(1, 45) h_hantush_classic = np.zeros(len(t)) for i in range(len(t)): h_hantush_classic[i] = hantush_classic(t[i], r=r, Q=20, T=T, S=S, c=c) # a = c * S b = r ** 2 / (4 * T * c) # hantush.step is normalized to go to 1, while the classic Hantush goes to # -Q / (2 * pi * T) * K0(r / lab) ht = hantush.step([1, a, b], dt=1, cutoff=0.99) * k0(r / lab) * (-Q / (2 * np.pi * T)) # plt.plot(t, h_hantush_classic, label='Hantush classic') plt.plot(np.arange(1, len(ht) + 1), ht, '--', label='Hantush Pastas') plt.legend(); """ Explanation: Hantush step function compared to classic Hantush function The classic Hantush function is $$ h(r, t) = \frac{-Q}{4\pi T}\int_u ^\infty \exp\left(-y - \frac{r^2}{4 \lambda^2 y} \right) \frac{\text{d}y}{y} $$ where $$ u=\frac{r^2 S}{4 T t} $$ For large time, the classic Hantush function goes to $$ \lim_{t\to\infty} h(r, t) = \frac{-Q}{2\pi T}\text{K}_0(r/\lambda) $$ where $\lambda^2=cT$. The classic Hantush function is a step function. The impulse response function $\theta$ is obtained by differentiation $$ \theta(t) = \frac{\partial h}{\partial t} = \frac{-Q}{4\pi Tt} \exp\left(\frac{-t}{cS} -\frac{r^2cS}{4cTt}\right) $$ The Hantush impulse response function used in Pastas is defined as $$ \theta(t) = A\frac{1}{2\text{K}_0(2\sqrt{b})} \frac{1}{t} e^{-t/a - ab/t} $$ Hence, the parameters in Pastas are related to the classic Hantush function as $$ A = -\frac{\text{K}_0(2\sqrt{b})}{2\pi T} $$ $$ a = cS $$ $$ b = \frac{r^2}{4\lambda^2} $$ End of explanation """ hantush = ps.Hantush(up=-1, meanstress=1, cutoff=0.999) hantushwm = ps.HantushWellModel(up=-1, meanstress=1, cutoff=0.999, distances=1) r = 1 h = hantush.step([1, a, b], dt=1, cutoff=0.99) hwm = hantushwm.step([1, a, b, r], dt=1, cutoff=0.99) plt.plot(h, label='Hantush') plt.plot(hwm, label='Hantush Well Model') plt.legend() plt.grid(); plt.plot(hwm / k0(np.sqrt(4 * r ** 2 * b)), '.') plt.axhline(k0(2 * r * np.sqrt(b)), linestyle='--', color='k'); hantush = ps.Hantush(up=-1, meanstress=1, cutoff=0.999) hantushwm = ps.HantushWellModel(up=-1, meanstress=1, cutoff=0.999, distances=1) r = 200 b = r ** 2 / (4 * lab ** 2) h = hantush.step([1, a, b], dt=1, cutoff=0.99) b = 1 / (4 * lab ** 2) hwm = hantushwm.step([1, a, b, r], dt=1, cutoff=0.99) plt.plot(h, label='Hantush') plt.plot(hwm, label='Hantush Well Model') plt.plot(hwm / k0(2 * r * np.sqrt(b)), '.', label='HantushWellModel corrected') plt.axhline(k0(np.sqrt(4 * r ** 2 * b)), linestyle='--', color='k') plt.legend() plt.grid(); """ Explanation: HantushWellModel step function in Pastas compared to classic Hantush function and Hantush function in Pastas The impulse response of the classic Hantush function is $$ \theta(t) = \frac{\partial h}{\partial t} = \frac{-Q}{4\pi Tt} \exp\left(\frac{-t}{cS} -\frac{r^2cS}{4cTt}\right) $$ The impulse response used for the HantushWellModel is The HantushWellModel impulse response function used in Pastas is defined as $$ \theta(t) = \frac{A}{2} \frac{1}{t} e^{-t/a - abr^2/t} $$ Hence, the parameters in Pastas are related to the classic Hantush function as $$ A = -\frac{1}{2\pi T} $$ $$ a = cS $$ $$ b = \frac{1}{4\lambda^2} $$ and the gain of the HantushWellModel is $$ A\text{K}_0(2r\sqrt{b}) $$ End of explanation """
ituethoslab/navcom-2017
exercises/Week 2-Qualitative Approaches to Quantitative Data/Exercises week 2.ipynb
gpl-3.0
import pandas as pd """ Explanation: Exercises week 2: Qualitative Approaches to Quantitative Data 1. We have seen network graphs We saw network graphs on the lecture. Where else have you seen them? What purpose do you remember they have served? Talk with neighbour for 10 min what do you think is necessary for making one. What is in a network graph, and what is needed. 2. DAMD data We have received DAMD data, let's explore it as a graph. End of explanation """ damd = pd.read_csv("20170718 hashtag_damd uncleaned.csv") damd.head(3) """ Explanation: If you place the data file in the same directory as this Notebook, it can be read into Python. End of explanation """ import networkx as nx # copy+paste the function definition below def buildHashtagCooccurrenceGraph(tweets): g = .... . . return g damd_graph = buildHashtagCooccurrenceGraph(damd) print(nx.info(damd_graph)) nx.write_gexf(damd_graph, "damd_graph.gexf") """ Explanation: Describe in words what is the shape of the data? What is an item of data? What do we know about each of the items? Do you already have an idea how would you like to start analyzing such data? 3. DAMD data as a graph To explore the DAMD data, let's conceptualize how rows are related to one another? Let's imagine a graph. Don't hesitate to grab pen+paper or the whiteboards. We can use Table 2 Net to build such a graph. The tool will give us a .gexf graph file. Build a bipartite graph, with tweet_id and hashtags as the two types of nodes, separating the latter by ;. Open .gexf file with you browser, what does it look like? Is it different shape that the .csv file? 3.1 Alternative graph creation in Python Ooh it so happens, that ETHOS Lab has a little code thing to turn a matrix to a graph. Please take a look. If you copypaste the buildHashtagCooccurrenceGraph function definition below and have run the code earlier in this notebook, you can create the graph in Python. End of explanation """
albahnsen/ML_SecurityInformatics
notebooks/02-IntroPython.ipynb
mit
import sys print('Python version:', sys.version) import IPython print('IPython:', IPython.__version__) import numpy print('numpy:', numpy.__version__) import scipy print('scipy:', scipy.__version__) import matplotlib print('matplotlib:', matplotlib.__version__) import pandas print('pandas:', pandas.__version__) import sklearn print('scikit-learn:', sklearn.__version__) """ Explanation: 02 - Introduction to Python for Data Analysis by Alejandro Correa Bahnsen version 0.2, May 2016 Part of the class Machine Learning for Security Informatics This notebook is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Special thanks goes to Rick Muller, Sandia National Laboratories Why Python? Python is the programming language of choice for many scientists to a large degree because it offers a great deal of power to analyze and model scientific data with relatively little overhead in terms of learning, installation or development time. It is a language you can pick up in a weekend, and use for the rest of one's life. The Python Tutorial is a great place to start getting a feel for the language. To complement this material, I taught a Python Short Course years ago to a group of computational chemists during a time that I was worried the field was moving too much in the direction of using canned software rather than developing one's own methods. I wanted to focus on what working scientists needed to be more productive: parsing output of other programs, building simple models, experimenting with object oriented programming, extending the language with C, and simple GUIs. I'm trying to do something very similar here, to cut to the chase and focus on what scientists need. In the last year or so, the Jupyter Project has put together a notebook interface that I have found incredibly valuable. A large number of people have released very good IPython Notebooks that I have taken a huge amount of pleasure reading through. Some ones that I particularly like include: Rick Muller A Crash Course in Python for Scientists Rob Johansson's excellent notebooks, including Scientific Computing with Python and Computational Quantum Physics with QuTiP lectures; XKCD style graphs in matplotlib; A collection of Notebooks for using IPython effectively A gallery of interesting IPython Notebooks I find Jupyter notebooks an easy way both to get important work done in my everyday job, as well as to communicate what I've done, how I've done it, and why it matters to my coworkers. In the interest of putting more notebooks out into the wild for other people to use and enjoy, I thought I would try to recreate some of what I was trying to get across in the original Python Short Course, updated by 15 years of Python, Numpy, Scipy, Pandas, Matplotlib, and IPython development, as well as my own experience in using Python almost every day of this time. Why Python for Data Analysis? Python is great for scripting and applications. The pandas library offers imporved library support. Scraping, web APIs Strong High Performance Computation support Load balanceing tasks MPI, GPU MapReduce Strong support for abstraction Intel MKL HDF5 Environment But we already know R ...Which is better? Hard to answer http://www.kdnuggets.com/2015/05/r-vs-python-data-science.html http://www.kdnuggets.com/2015/03/the-grammar-data-science-python-vs-r.html https://www.datacamp.com/community/tutorials/r-or-python-for-data-analysis https://www.dataquest.io/blog/python-vs-r/ http://www.dataschool.io/python-or-r-for-data-science/ What You Need to Install There are two branches of current releases in Python: the older-syntax Python 2, and the newer-syntax Python 3. This schizophrenia is largely intentional: when it became clear that some non-backwards-compatible changes to the language were necessary, the Python dev-team decided to go through a five-year (or so) transition, during which the new language features would be introduced and the old language was still actively maintained, to make such a transition as easy as possible. Nonetheless, I'm going to write these notes with Python 3 in mind, since this is the version of the language that I use in my day-to-day job, and am most comfortable with. With this in mind, these notes assume you have a Python distribution that includes: Python version 3.5; Numpy, the core numerical extensions for linear algebra and multidimensional arrays; Scipy, additional libraries for scientific programming; Matplotlib, excellent plotting and graphing libraries; IPython, with the additional libraries required for the notebook interface. Pandas, Python version of R dataframe scikit-learn, Machine learning library! A good, easy to install option that supports Mac, Windows, and Linux, and that has all of these packages (and much more) is the Anaconda. Checking your installation You can run the following code to check the versions of the packages on your system: (in IPython notebook, press shift and return together to execute the contents of a cell) End of explanation """ 2+2 (50-5*6)/4 """ Explanation: I. Python Overview This is a quick introduction to Python. There are lots of other places to learn the language more thoroughly. I have collected a list of useful links, including ones to other learning resources, at the end of this notebook. If you want a little more depth, Python Tutorial is a great place to start, as is Zed Shaw's Learn Python the Hard Way. The lessons that follow make use of the IPython notebooks. There's a good introduction to notebooks in the IPython notebook documentation that even has a nice video on how to use the notebooks. You should probably also flip through the IPython tutorial in your copious free time. Briefly, notebooks have code cells (that are generally followed by result cells) and text cells. The text cells are the stuff that you're reading now. The code cells start with "In []:" with some number generally in the brackets. If you put your cursor in the code cell and hit Shift-Enter, the code will run in the Python interpreter and the result will print out in the output cell. You can then change things around and see whether you understand what's going on. If you need to know more, see the IPython notebook documentation or the IPython tutorial. Using Python as a Calculator Many of the things I used to use a calculator for, I now use Python for: End of explanation """ sqrt(81) from math import sqrt sqrt(81) """ Explanation: (If you're typing this into an IPython notebook, or otherwise using notebook file, you hit shift-Enter to evaluate a cell.) In the last few lines, we have sped by a lot of things that we should stop for a moment and explore a little more fully. We've seen, however briefly, two different data types: integers, also known as whole numbers to the non-programming world, and floating point numbers, also known (incorrectly) as decimal numbers to the rest of the world. We've also seen the first instance of an import statement. Python has a huge number of libraries included with the distribution. To keep things simple, most of these variables and functions are not accessible from a normal Python interactive session. Instead, you have to import the name. For example, there is a math module containing many useful functions. To access, say, the square root function, you can either first from math import sqrt and then End of explanation """ import math math.sqrt(81) """ Explanation: or you can simply import the math library itself End of explanation """ radius = 20 pi = math.pi area = pi * radius ** 2 area """ Explanation: You can define variables using the equals (=) sign: End of explanation """ volume """ Explanation: If you try to access a variable that you haven't yet defined, you get an error: End of explanation """ volume = 4/3*pi*radius**3 volume """ Explanation: and you need to define it: End of explanation """ return = 0 """ Explanation: You can name a variable almost anything you want. It needs to start with an alphabetical character or "_", can contain alphanumeric charcters plus underscores ("_"). Certain words, however, are reserved for the language: and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield Trying to define a variable using one of these will result in a syntax error: End of explanation """ 'Hello, World!' """ Explanation: The Python Tutorial has more on using Python as an interactive shell. The IPython tutorial makes a nice complement to this, since IPython has a much more sophisticated iteractive shell. Strings Strings are lists of printable characters, and can be defined using either single quotes End of explanation """ "Hello, World!" """ Explanation: or double quotes End of explanation """ "He's a Rebel" 'She asked, "How are you today?"' """ Explanation: But not both at the same time, unless you want one of the symbols to be part of the string. End of explanation """ greeting = "Hello, World!" """ Explanation: Just like the other two data objects we're familiar with (ints and floats), you can assign a string to a variable End of explanation """ print(greeting) """ Explanation: The print statement is often used for printing character strings: End of explanation """ print("The area is " + area) print("The area is " + str(area)) """ Explanation: But it can also print data types other than strings: End of explanation """ statement = "Hello," + "World!" print(statement) """ Explanation: In the above snipped, the number 600 (stored in the variable "area") is converted into a string before being printed out. You can use the + operator to concatenate strings together: End of explanation """ statement = "Hello, " + "World!" print(statement) """ Explanation: Don't forget the space between the strings, if you want one there. End of explanation """ print("This " + "is " + "a " + "longer " + "statement.") """ Explanation: You can use + to concatenate multiple strings in a single statement: End of explanation """ days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] """ Explanation: If you have a lot of words to concatenate together, there are other, more efficient ways to do this. But this is fine for linking a few strings together. Lists Very often in a programming language, one wants to keep a group of similar items together. Python does this using a data type called lists. End of explanation """ days_of_the_week[2] """ Explanation: You can access members of the list using the index of that item: End of explanation """ days_of_the_week[-1] """ Explanation: Python lists, like C, but unlike Fortran, use 0 as the index of the first element of a list. Thus, in this example, the 0 element is "Sunday", 1 is "Monday", and so on. If you need to access the nth element from the end of the list, you can use a negative index. For example, the -1 element of a list is the last element: End of explanation """ languages = ["Fortran","C","C++"] languages.append("Python") print(languages) """ Explanation: You can add additional items to the list using the .append() command: End of explanation """ list(range(10)) """ Explanation: The range() command is a convenient way to make sequential lists of numbers: End of explanation """ list(range(2,8)) """ Explanation: Note that range(n) starts at 0 and gives the sequential list of integers less than n. If you want to start at a different number, use range(start,stop) End of explanation """ evens = list(range(0,20,2)) evens evens[3] """ Explanation: The lists created above with range have a step of 1 between elements. You can also give a fixed step size via a third command: End of explanation """ ["Today",7,99.3,""] """ Explanation: Lists do not have to hold the same data type. For example, End of explanation """ help(len) len(evens) """ Explanation: However, it's good (but not essential) to use lists for similar objects that are somehow logically connected. If you want to group different data types together into a composite data object, it's best to use tuples, which we will learn about below. You can find out how long a list is using the len() command: End of explanation """ for day in days_of_the_week: print(day) """ Explanation: Iteration, Indentation, and Blocks One of the most useful things you can do with lists is to iterate through them, i.e. to go through each element one at a time. To do this in Python, we use the for statement: End of explanation """ for day in days_of_the_week: statement = "Today is " + day print(statement) """ Explanation: This code snippet goes through each element of the list called days_of_the_week and assigns it to the variable day. It then executes everything in the indented block (in this case only one line of code, the print statement) using those variable assignments. When the program has gone through every element of the list, it exists the block. (Almost) every programming language defines blocks of code in some way. In Fortran, one uses END statements (ENDDO, ENDIF, etc.) to define code blocks. In C, C++, and Perl, one uses curly braces {} to define these blocks. Python uses a colon (":"), followed by indentation level to define code blocks. Everything at a higher level of indentation is taken to be in the same block. In the above example the block was only a single line, but we could have had longer blocks as well: End of explanation """ for i in range(20): print("The square of ",i," is ",i*i) """ Explanation: The range() command is particularly useful with the for statement to execute loops of a specified length: End of explanation """ for letter in "Sunday": print(letter) """ Explanation: Slicing Lists and strings have something in common that you might not suspect: they can both be treated as sequences. You already know that you can iterate through the elements of a list. You can also iterate through the letters in a string: End of explanation """ days_of_the_week[0] """ Explanation: This is only occasionally useful. Slightly more useful is the slicing operation, which you can also use on any sequence. We already know that we can use indexing to get the first element of a list: End of explanation """ days_of_the_week[0:2] """ Explanation: If we want the list containing the first two elements of a list, we can do this via End of explanation """ days_of_the_week[:2] """ Explanation: or simply End of explanation """ days_of_the_week[-2:] """ Explanation: If we want the last items of the list, we can do this with negative slicing: End of explanation """ workdays = days_of_the_week[1:6] print(workdays) """ Explanation: which is somewhat logically consistent with negative indices accessing the last elements of the list. You can do: End of explanation """ day = "Sunday" abbreviation = day[:3] print(abbreviation) """ Explanation: Since strings are sequences, you can also do this to them: End of explanation """ numbers = list(range(0,40)) evens = numbers[2::2] evens """ Explanation: If we really want to get fancy, we can pass a third element into the slice, which specifies a step length (just like a third argument to the range() function specifies the step): End of explanation """ if day == "Sunday": print("Sleep in") else: print("Go to work") """ Explanation: Note that in this example I was even able to omit the second argument, so that the slice started at 2, went to the end of the list, and took every second element, to generate the list of even numbers less that 40. Booleans and Truth Testing We have now learned a few data types. We have integers and floating point numbers, strings, and lists to contain them. We have also learned about lists, a container that can hold any data type. We have learned to print things out, and to iterate over items in lists. We will now learn about boolean variables that can be either True or False. We invariably need some concept of conditions in programming to control branching behavior, to allow a program to react differently to different situations. If it's Monday, I'll go to work, but if it's Sunday, I'll sleep in. To do this in Python, we use a combination of boolean variables, which evaluate to either True or False, and if statements, that control branching based on boolean values. For example: End of explanation """ day == "Sunday" """ Explanation: (Quick quiz: why did the snippet print "Go to work" here? What is the variable "day" set to?) Let's take the snippet apart to see what happened. First, note the statement End of explanation """ 1 == 2 50 == 2*25 3 < 3.14159 1 == 1.0 1 != 0 1 <= 2 1 >= 1 """ Explanation: If we evaluate it by itself, as we just did, we see that it returns a boolean value, False. The "==" operator performs equality testing. If the two items are equal, it returns True, otherwise it returns False. In this case, it is comparing two variables, the string "Sunday", and whatever is stored in the variable "day", which, in this case, is the other string "Saturday". Since the two strings are not equal to each other, the truth test has the false value. The if statement that contains the truth test is followed by a code block (a colon followed by an indented block of code). If the boolean is true, it executes the code in that block. Since it is false in the above example, we don't see that code executed. The first block of code is followed by an else statement, which is executed if nothing else in the above if statement is true. Since the value was false, this code is executed, which is why we see "Go to work". You can compare any data types in Python: End of explanation """ 1 is 1.0 """ Explanation: We see a few other boolean operators here, all of which which should be self-explanatory. Less than, equality, non-equality, and so on. Particularly interesting is the 1 == 1.0 test, which is true, since even though the two objects are different data types (integer and floating point number), they have the same value. There is another boolean operator is, that tests whether two objects are the same object: End of explanation """ [1,2,3] == [1,2,4] [1,2,3] < [1,2,4] """ Explanation: We can do boolean tests on lists as well: End of explanation """ hours = 5 0 < hours < 24 """ Explanation: Finally, note that you can also string multiple comparisons together, which can result in very intuitive tests: End of explanation """ if day == "Sunday": print("Sleep in") elif day == "Saturday": print("Do chores") else: print("Go to work") """ Explanation: If statements can have elif parts ("else if"), in addition to if/else parts. For example: End of explanation """ for day in days_of_the_week: statement = "Today is " + day print(statement) if day == "Sunday": print(" Sleep in") elif day == "Saturday": print(" Do chores") else: print(" Go to work") """ Explanation: Of course we can combine if statements with for loops, to make a snippet that is almost interesting: End of explanation """ bool(1) bool(0) bool(["This "," is "," a "," list"]) """ Explanation: This is something of an advanced topic, but ordinary data types have boolean values associated with them, and, indeed, in early versions of Python there was not a separate boolean object. Essentially, anything that was a 0 value (the integer or floating point 0, an empty string "", or an empty list []) was False, and everything else was true. You can see the boolean value of any data object using the bool() function. End of explanation """ n = 10 sequence = [0,1] for i in range(2,n): # This is going to be a problem if we ever set n <= 2! sequence.append(sequence[i-1]+sequence[i-2]) print(sequence) """ Explanation: Code Example: The Fibonacci Sequence The Fibonacci sequence is a sequence in math that starts with 0 and 1, and then each successive entry is the sum of the previous two. Thus, the sequence goes 0,1,1,2,3,5,8,13,21,34,55,89,... A very common exercise in programming books is to compute the Fibonacci sequence up to some number n. First I'll show the code, then I'll discuss what it is doing. End of explanation """ def fibonacci(sequence_length): "Return the Fibonacci sequence of length *sequence_length*" sequence = [0,1] if sequence_length < 1: print("Fibonacci sequence only defined for length 1 or greater") return if 0 < sequence_length < 3: return sequence[:sequence_length] for i in range(2,sequence_length): sequence.append(sequence[i-1]+sequence[i-2]) return sequence """ Explanation: Let's go through this line by line. First, we define the variable n, and set it to the integer 20. n is the length of the sequence we're going to form, and should probably have a better variable name. We then create a variable called sequence, and initialize it to the list with the integers 0 and 1 in it, the first two elements of the Fibonacci sequence. We have to create these elements "by hand", since the iterative part of the sequence requires two previous elements. We then have a for loop over the list of integers from 2 (the next element of the list) to n (the length of the sequence). After the colon, we see a hash tag "#", and then a comment that if we had set n to some number less than 2 we would have a problem. Comments in Python start with #, and are good ways to make notes to yourself or to a user of your code explaining why you did what you did. Better than the comment here would be to test to make sure the value of n is valid, and to complain if it isn't; we'll try this later. In the body of the loop, we append to the list an integer equal to the sum of the two previous elements of the list. After exiting the loop (ending the indentation) we then print out the whole list. That's it! Functions We might want to use the Fibonacci snippet with different sequence lengths. We could cut an paste the code into another cell, changing the value of n, but it's easier and more useful to make a function out of the code. We do this with the def statement in Python: End of explanation """ fibonacci(2) fibonacci(12) """ Explanation: We can now call fibonacci() for different sequence_lengths: End of explanation """ help(fibonacci) """ Explanation: We've introduced a several new features here. First, note that the function itself is defined as a code block (a colon followed by an indented block). This is the standard way that Python delimits things. Next, note that the first line of the function is a single string. This is called a docstring, and is a special kind of comment that is often available to people using the function through the python command line: End of explanation """ t = (1,2,'hi',9.0) t """ Explanation: If you define a docstring for all of your functions, it makes it easier for other people to use them, since they can get help on the arguments and return values of the function. Next, note that rather than putting a comment in about what input values lead to errors, we have some testing of these values, followed by a warning if the value is invalid, and some conditional code to handle special cases. Two More Data Structures: Tuples and Dictionaries Before we end the Python overview, I wanted to touch on two more data structures that are very useful (and thus very common) in Python programs. A tuple is a sequence object like a list or a string. It's constructed by grouping a sequence of objects together with commas, either without brackets, or with parentheses: End of explanation """ t[1] """ Explanation: Tuples are like lists, in that you can access the elements using indices: End of explanation """ t.append(7) t[1]=77 """ Explanation: However, tuples are immutable, you can't append to them or change the elements of them: End of explanation """ ('Bob',0.0,21.0) """ Explanation: Tuples are useful anytime you want to group different pieces of data together in an object, but don't want to create a full-fledged class (see below) for them. For example, let's say you want the Cartesian coordinates of some objects in your program. Tuples are a good way to do this: End of explanation """ positions = [ ('Bob',0.0,21.0), ('Cat',2.5,13.1), ('Dog',33.0,1.2) ] """ Explanation: Again, it's not a necessary distinction, but one way to distinguish tuples and lists is that tuples are a collection of different things, here a name, and x and y coordinates, whereas a list is a collection of similar things, like if we wanted a list of those coordinates: End of explanation """ def minmax(objects): minx = 1e20 # These are set to really big numbers miny = 1e20 for obj in objects: name,x,y = obj if x < minx: minx = x if y < miny: miny = y return minx,miny x,y = minmax(positions) print(x,y) """ Explanation: Tuples can be used when functions return more than one value. Say we wanted to compute the smallest x- and y-coordinates of the above list of objects. We could write: End of explanation """ mylist = [1,2,9,21] """ Explanation: Dictionaries are an object called "mappings" or "associative arrays" in other languages. Whereas a list associates an integer index with a set of objects: End of explanation """ ages = {"Rick": 46, "Bob": 86, "Fred": 21} print("Rick's age is ",ages["Rick"]) """ Explanation: The index in a dictionary is called the key, and the corresponding dictionary entry is the value. A dictionary can use (almost) anything as the key. Whereas lists are formed with square brackets [], dictionaries use curly brackets {}: End of explanation """ dict(Rick=46,Bob=86,Fred=20) """ Explanation: There's also a convenient way to create dictionaries without having to quote the keys. End of explanation """ len(t) len(ages) """ Explanation: The len() command works on both tuples and dictionaries: End of explanation """ import this """ Explanation: Conclusion of the Python Overview There is, of course, much more to the language than I've covered here. I've tried to keep this brief enough so that you can jump in and start using Python to simplify your life and work. My own experience in learning new things is that the information doesn't "stick" unless you try and use it for something in real life. You will no doubt need to learn more as you go. I've listed several other good references, including the Python Tutorial and Learn Python the Hard Way. Additionally, now is a good time to start familiarizing yourself with the Python Documentation, and, in particular, the Python Language Reference. Tim Peters, one of the earliest and most prolific Python contributors, wrote the "Zen of Python", which can be accessed via the "import this" command: End of explanation """ import numpy as np import scipy as sp array = np.array([1,2,3,4,5,6]) array """ Explanation: No matter how experienced a programmer you are, these are words to meditate on. II. Numpy and Scipy Numpy contains core routines for doing fast vector, matrix, and linear algebra-type operations in Python. Scipy contains additional routines for optimization, special functions, and so on. Both contain modules written in C and Fortran so that they're as fast as possible. Together, they give Python roughly the same capability that the Matlab program offers. (In fact, if you're an experienced Matlab user, there a guide to Numpy for Matlab users just for you.) Making vectors and matrices Fundamental to both Numpy and Scipy is the ability to work with vectors and matrices. You can create vectors from lists using the array command: End of explanation """ array.shape """ Explanation: size of the array End of explanation """ mat = np.array([[0,1],[1,0]]) mat """ Explanation: To build matrices, you can either use the array command with lists of lists: End of explanation """ mat2 = np.c_[mat, np.ones(2)] mat2 """ Explanation: Add a column of ones to mat End of explanation """ mat2.shape """ Explanation: size of a matrix End of explanation """ np.zeros((3,3)) """ Explanation: You can also form empty (zero) matrices of arbitrary shape (including vectors, which Numpy treats as vectors with one row), using the zeros command: End of explanation """ np.identity(4) """ Explanation: There's also an identity command that behaves as you'd expect: End of explanation """ np.linspace(0,1) """ Explanation: as well as a ones command. Linspace, matrix functions, and plotting The linspace command makes a linear array of points from a starting to an ending value. End of explanation """ np.linspace(0,1,11) """ Explanation: If you provide a third argument, it takes that as the number of points in the space. If you don't provide the argument, it gives a length 50 linear space. End of explanation """ x = np.linspace(0,2*np.pi) np.sin(x) """ Explanation: linspace is an easy way to make coordinates for plotting. Functions in the numpy library (all of which are imported into IPython notebook) can act on an entire vector (or even a matrix) of points at once. Thus, End of explanation """ %matplotlib inline import matplotlib.pyplot as plt plt.plot(x,np.sin(x)) """ Explanation: In conjunction with matplotlib, this is a nice way to plot things: End of explanation """ 0.125*np.identity(3) """ Explanation: Matrix operations Matrix objects act sensibly when multiplied by scalars: End of explanation """ np.identity(2) + np.array([[1,1],[1,2]]) """ Explanation: as well as when you add two matrices together. (However, the matrices have to be the same shape.) End of explanation """ np.identity(2)*np.ones((2,2)) """ Explanation: Something that confuses Matlab users is that the times (*) operator give element-wise multiplication rather than matrix multiplication: End of explanation """ np.dot(np.identity(2),np.ones((2,2))) """ Explanation: To get matrix multiplication, you need the dot command: End of explanation """ v = np.array([3,4]) np.sqrt(np.dot(v,v)) """ Explanation: dot can also do dot products (duh!): End of explanation """ m = np.array([[1,2],[3,4]]) m.T np.linalg.inv(m) """ Explanation: as well as matrix-vector products. There are determinant, inverse, and transpose functions that act as you would suppose. Transpose can be abbreviated with ".T" at the end of a matrix object: End of explanation """ np.diag([1,2,3,4,5]) """ Explanation: There's also a diag() function that takes a list or a vector and puts it along the diagonal of a square matrix. End of explanation """ raw_data = """\ 3.1905781584582433,0.028208609537968457 4.346895074946466,0.007160804747670053 5.374732334047101,0.0046962988461934805 8.201284796573875,0.0004614473299618756 10.899357601713055,0.00005038370219939726 16.295503211991434,4.377451812785309e-7 21.82012847965739,3.0799922117601088e-9 32.48394004282656,1.524776208284536e-13 43.53319057815846,5.5012073588707224e-18""" """ Explanation: We'll find this useful later on. Least squares fitting Very often we deal with some data that we want to fit to some sort of expected behavior. Say we have the following: End of explanation """ data = [] for line in raw_data.splitlines(): words = line.split(',') data.append(words) data = np.array(data, dtype=np.float) data data[:, 0] plt.title("Raw Data") plt.xlabel("Distance") plt.plot(data[:,0],data[:,1],'bo') """ Explanation: There's a section below on parsing CSV data. We'll steal the parser from that. For an explanation, skip ahead to that section. Otherwise, just assume that this is a way to parse that text into a numpy array that we can plot and do other analyses with. End of explanation """ plt.title("Raw Data") plt.xlabel("Distance") plt.semilogy(data[:,0],data[:,1],'bo') """ Explanation: Since we expect the data to have an exponential decay, we can plot it using a semi-log plot. End of explanation """ params = sp.polyfit(data[:,0],np.log(data[:,1]),1) a = params[0] A = np.exp(params[1]) """ Explanation: For a pure exponential decay like this, we can fit the log of the data to a straight line. The above plot suggests this is a good approximation. Given a function $$ y = Ae^{-ax} $$ $$ \log(y) = \log(A) - ax$$ Thus, if we fit the log of the data versus x, we should get a straight line with slope $a$, and an intercept that gives the constant $A$. There's a numpy function called polyfit that will fit data to a polynomial form. We'll use this to fit to a straight line (a polynomial of order 1) End of explanation """ x = np.linspace(1,45) plt.title("Raw Data") plt.xlabel("Distance") plt.semilogy(data[:,0],data[:,1],'bo') plt.semilogy(x,A*np.exp(a*x),'b-') """ Explanation: Let's see whether this curve fits the data. End of explanation """ gauss_data = """\ -0.9902286902286903,1.4065274110372852e-19 -0.7566104566104566,2.2504438576596563e-18 -0.5117810117810118,1.9459459459459454 -0.31887271887271884,10.621621621621626 -0.250997150997151,15.891891891891893 -0.1463309463309464,23.756756756756754 -0.07267267267267263,28.135135135135133 -0.04426734426734419,29.02702702702703 -0.0015939015939017698,29.675675675675677 0.04689304689304685,29.10810810810811 0.0840994840994842,27.324324324324326 0.1700546700546699,22.216216216216214 0.370878570878571,7.540540540540545 0.5338338338338338,1.621621621621618 0.722014322014322,0.08108108108108068 0.9926849926849926,-0.08108108108108646""" data = [] for line in gauss_data.splitlines(): words = line.split(',') data.append(words) data = np.array(data, dtype=np.float) plt.plot(data[:,0],data[:,1],'bo') """ Explanation: If we have more complicated functions, we may not be able to get away with fitting to a simple polynomial. Consider the following data: End of explanation """ def gauss(x,A,a): return A*np.exp(a*x**2) """ Explanation: This data looks more Gaussian than exponential. If we wanted to, we could use polyfit for this as well, but let's use the curve_fit function from Scipy, which can fit to arbitrary functions. You can learn more using help(curve_fit). First define a general Gaussian function to fit to. End of explanation """ from scipy.optimize import curve_fit params,conv = curve_fit(gauss,data[:,0],data[:,1]) x = np.linspace(-1,1) plt.plot(data[:,0],data[:,1],'bo') A,a = params plt.plot(x,gauss(x,A,a),'b-') """ Explanation: Now fit to it using curve_fit: End of explanation """ from random import random rands = [] for i in range(100): rands.append(random()) plt.plot(rands) """ Explanation: The curve_fit routine we just used is built on top of a very good general minimization capability in Scipy. You can learn more at the scipy documentation pages. Monte Carlo and random numbers Many methods in scientific computing rely on Monte Carlo integration, where a sequence of (pseudo) random numbers are used to approximate the integral of a function. Python has good random number generators in the standard library. The random() function gives pseudorandom numbers uniformly distributed between 0 and 1: End of explanation """ from random import gauss grands = [] for i in range(100): grands.append(gauss(0,1)) plt.plot(grands) """ Explanation: random() uses the Mersenne Twister algorithm, which is a highly regarded pseudorandom number generator. There are also functions to generate random integers, to randomly shuffle a list, and functions to pick random numbers from a particular distribution, like the normal distribution: End of explanation """ plt.plot(np.random.rand(100)) """ Explanation: It is generally more efficient to generate a list of random numbers all at once, particularly if you're drawing from a non-uniform distribution. Numpy has functions to generate vectors and matrices of particular types of random distributions. End of explanation """ data.shape """ Explanation: Slicing numpy arrays and matrices End of explanation """ data[:, 1] """ Explanation: Select second column End of explanation """ data[:5, :] """ Explanation: Select the first 5 rows End of explanation """ data[1, -1] """ Explanation: Select the second row and the last column End of explanation """ myoutput = """\ @ Step Energy Delta E Gmax Grms Xrms Xmax Walltime @ ---- ---------------- -------- -------- -------- -------- -------- -------- @ 0 -6095.12544083 0.0D+00 0.03686 0.00936 0.00000 0.00000 1391.5 @ 1 -6095.25762870 -1.3D-01 0.00732 0.00168 0.32456 0.84140 10468.0 @ 2 -6095.26325979 -5.6D-03 0.00233 0.00056 0.06294 0.14009 11963.5 @ 3 -6095.26428124 -1.0D-03 0.00109 0.00024 0.03245 0.10269 13331.9 @ 4 -6095.26463203 -3.5D-04 0.00057 0.00013 0.02737 0.09112 14710.8 @ 5 -6095.26477615 -1.4D-04 0.00043 0.00009 0.02259 0.08615 20211.1 @ 6 -6095.26482624 -5.0D-05 0.00015 0.00002 0.00831 0.03147 21726.1 @ 7 -6095.26483584 -9.6D-06 0.00021 0.00004 0.01473 0.05265 24890.5 @ 8 -6095.26484405 -8.2D-06 0.00005 0.00001 0.00555 0.01929 26448.7 @ 9 -6095.26484599 -1.9D-06 0.00003 0.00001 0.00164 0.00564 27258.1 @ 10 -6095.26484676 -7.7D-07 0.00003 0.00001 0.00161 0.00553 28155.3 @ 11 -6095.26484693 -1.8D-07 0.00002 0.00000 0.00054 0.00151 28981.7 @ 11 -6095.26484693 -1.8D-07 0.00002 0.00000 0.00054 0.00151 28981.7""" """ Explanation: III. Intermediate Python Output Parsing As more and more of our day-to-day work is being done on and through computers, we increasingly have output that one program writes, often in a text file, that we need to analyze in one way or another, and potentially feed that output into another file. Suppose we have the following output: End of explanation """ lines = myoutput.splitlines() lines """ Explanation: This output actually came from a geometry optimization of a Silicon cluster using the NWChem quantum chemistry suite. At every step the program computes the energy of the molecular geometry, and then changes the geometry to minimize the computed forces, until the energy converges. I obtained this output via the unix command % grep @ nwchem.out since NWChem is nice enough to precede the lines that you need to monitor job progress with the '@' symbol. We could do the entire analysis in Python; I'll show how to do this later on, but first let's focus on turning this code into a usable Python object that we can plot. First, note that the data is entered into a multi-line string. When Python sees three quote marks """ or ''' it treats everything following as part of a single string, including newlines, tabs, and anything else, until it sees the same three quote marks (""" has to be followed by another """, and ''' has to be followed by another ''') again. This is a convenient way to quickly dump data into Python, and it also reinforces the important idea that you don't have to open a file and deal with it one line at a time. You can read everything in, and deal with it as one big chunk. The first thing we'll do, though, is to split the big string into a list of strings, since each line corresponds to a separate piece of data. We will use the splitlines() function on the big myout string to break it into a new element every time it sees a newline (\n) character: End of explanation """ for line in lines[2:]: # do something with each line words = line.split() """ Explanation: Splitting is a big concept in text processing. We used splitlines() here, and we will use the more general split() function below to split each line into whitespace-delimited words. We now want to do three things: Skip over the lines that don't carry any information Break apart each line that does carry information and grab the pieces we want Turn the resulting data into something that we can plot. For this data, we really only want the Energy column, the Gmax column (which contains the maximum gradient at each step), and perhaps the Walltime column. Since the data is now in a list of lines, we can iterate over it: End of explanation """ lines[2].split() """ Explanation: Let's examine what we just did: first, we used a for loop to iterate over each line. However, we skipped the first two (the lines[2:] only takes the lines starting from index 2), since lines[0] contained the title information, and lines[1] contained underscores. We then split each line into chunks (which we're calling "words", even though in most cases they're numbers) using the string split() command. Here's what split does: End of explanation """ for line in lines[2:]: # do something with each line words = line.split() energy = words[2] gmax = words[4] time = words[8] print(energy,gmax,time) """ Explanation: This is almost exactly what we want. We just have to now pick the fields we want: End of explanation """ data = [] for line in lines[2:]: # do something with each line words = line.split() energy = float(words[2]) gmax = float(words[4]) time = float(words[8]) data.append((energy,gmax,time)) data = np.array(data) """ Explanation: This is fine for printing things out, but if we want to do something with the data, either make a calculation with it or pass it into a plotting, we need to convert the strings into regular floating point numbers. We can use the float() command for this. We also need to save it in some form. I'll do this as follows: End of explanation """ plt.plot(data[:,0]) plt.xlabel('step') plt.ylabel('Energy (hartrees)') plt.title('Convergence of NWChem geometry optimization for Si cluster') energies = data[:,0] minE = min(energies) energies_eV = 27.211*(energies-minE) plt.plot(energies_eV) plt.xlabel('step') plt.ylabel('Energy (eV)') plt.title('Convergence of NWChem geometry optimization for Si cluster') """ Explanation: We now have our data in a numpy array, so we can choose columns to print: End of explanation """ lines = """\ ---------------------------------------- | WALL | 0.45 | 443.61 | ---------------------------------------- @ Step Energy Delta E Gmax Grms Xrms Xmax Walltime @ ---- ---------------- -------- -------- -------- -------- -------- -------- @ 0 -6095.12544083 0.0D+00 0.03686 0.00936 0.00000 0.00000 1391.5 ok ok Z-matrix (autoz) -------- """.splitlines() for line in lines: if line.startswith('@'): print(line) """ Explanation: This gives us the output in a form that we can think about: 4 eV is a fairly substantial energy change (chemical bonds are roughly this magnitude of energy), and most of the energy decrease was obtained in the first geometry iteration. We mentioned earlier that we don't have to rely on grep to pull out the relevant lines for us. The string module has a lot of useful functions we can use for this. Among them is the startswith function. For example: End of explanation """ np.linspace(0,1) """ Explanation: and we've successfully grabbed all of the lines that begin with the @ symbol. The real value in a language like Python is that it makes it easy to take additional steps to analyze data in this fashion, which means you are thinking more about your data, and are more likely to see important patterns. Optional arguments You will recall that the linspace function can take either two arguments (for the starting and ending points): End of explanation """ np.linspace(0,1,5) """ Explanation: or it can take three arguments, for the starting point, the ending point, and the number of points: End of explanation """ np.linspace(0,1,5,endpoint=False) """ Explanation: You can also pass in keywords to exclude the endpoint: End of explanation """ def my_linspace(start,end): npoints = 50 v = [] d = (end-start)/float(npoints-1) for i in range(npoints): v.append(start + i*d) return v my_linspace(0,1) """ Explanation: Right now, we only know how to specify functions that have a fixed number of arguments. We'll learn how to do the more general cases here. If we're defining a simple version of linspace, we would start with: End of explanation """ def my_linspace(start,end,npoints = 50): v = [] d = (end-start)/float(npoints-1) for i in range(npoints): v.append(start + i*d) return v """ Explanation: We can add an optional argument by specifying a default value in the argument list: End of explanation """ my_linspace(0,1) """ Explanation: This gives exactly the same result if we don't specify anything: End of explanation """ my_linspace(0,1,5) """ Explanation: But also let's us override the default value with a third argument: End of explanation """ def my_linspace(start,end,npoints=50,**kwargs): endpoint = kwargs.get('endpoint',True) v = [] if endpoint: d = (end-start)/float(npoints-1) else: d = (end-start)/float(npoints) for i in range(npoints): v.append(start + i*d) return v my_linspace(0,1,5,endpoint=False) """ Explanation: We can add arbitrary keyword arguments to the function definition by putting a keyword argument **kwargs handle in: End of explanation """ def my_range(*args): start = 0 step = 1 if len(args) == 1: end = args[0] elif len(args) == 2: start,end = args elif len(args) == 3: start,end,step = args else: raise Exception("Unable to parse arguments") v = [] value = start while True: v.append(value) value += step if value > end: break return v """ Explanation: What the keyword argument construction does is to take any additional keyword arguments (i.e. arguments specified by name, like "endpoint=False"), and stick them into a dictionary called "kwargs" (you can call it anything you like, but it has to be preceded by two stars). You can then grab items out of the dictionary using the get command, which also lets you specify a default value. I realize it takes a little getting used to, but it is a common construction in Python code, and you should be able to recognize it. There's an analogous *args that dumps any additional arguments into a list called "args". Think about the range function: it can take one (the endpoint), two (starting and ending points), or three (starting, ending, and step) arguments. How would we define this? End of explanation """ my_range() """ Explanation: Note that we have defined a few new things you haven't seen before: a break statement, that allows us to exit a for loop if some conditions are met, and an exception statement, that causes the interpreter to exit with an error message. For example: End of explanation """ evens1 = [2*i for i in range(10)] print(evens1) """ Explanation: List Comprehensions and Generators List comprehensions are a streamlined way to make lists. They look something like a list definition, with some logic thrown in. For example: End of explanation """ odds = [i for i in range(20) if i%2==1] odds """ Explanation: You can also put some boolean testing into the construct: End of explanation """ def evens_below(n): for i in range(n): if i%2 == 0: yield i return for i in evens_below(9): print(i) """ Explanation: Here i%2 is the remainder when i is divided by 2, so that i%2==1 is true if the number is odd. Even though this is a relative new addition to the language, it is now fairly common since it's so convenient. iterators are a way of making virtual sequence objects. Consider if we had the nested loop structure: for i in range(1000000): for j in range(1000000): Inside the main loop, we make a list of 1,000,000 integers, just to loop over them one at a time. We don't need any of the additional things that a lists gives us, like slicing or random access, we just need to go through the numbers one at a time. And we're making 1,000,000 of them. iterators are a way around this. For example, the xrange function is the iterator version of range. This simply makes a counter that is looped through in sequence, so that the analogous loop structure would look like: for i in xrange(1000000): for j in xrange(1000000): Even though we've only added two characters, we've dramatically sped up the code, because we're not making 1,000,000 big lists. We can define our own iterators using the yield statement: End of explanation """ list(evens_below(9)) """ Explanation: We can always turn an iterator into a list using the list command: End of explanation """ evens_gen = (i for i in range(9) if i%2==0) for i in evens_gen: print(i) """ Explanation: There's a special syntax called a generator expression that looks a lot like a list comprehension: End of explanation """
empet/Plotly-plots
Tri-Surf-Plotly.ipynb
gpl-3.0
import numpy as np from scipy.spatial import Delaunay import plotly.plotly as py py.sign_in('empet','api_key') u=np.linspace(0,2*np.pi, 24) v=np.linspace(-1,1, 8) u,v=np.meshgrid(u,v) u=u.flatten() v=v.flatten() #evaluate the parameterization at the flattened u and v tp=1+0.5*v*np.cos(u/2.) x=tp*np.cos(u) y=tp*np.sin(u) z=0.5*v*np.sin(u/2.) #define 2D points, as input data for the Delaunay triangulation of U points2D=np.vstack([u,v]).T tri = Delaunay(points2D)#triangulate the rectangle U points3D=np.vstack((x,y,z)).T """ Explanation: Plotting trisurfs with Plotly A triangulation of a compact surface is a finite collection of triangles that cover the surface in such a way that every point on the surface is in a triangle, and the intersection of any two triangles is either void, a common edge or a common vertex. A triangulated surface is called tri-surface. The triangulation of a surface defined as the graph of a continuous function, $z=f(x,y), (x,y)\in D\subset\mathbb{R}^2$ or in a parametric form: $$x=x(u,v), y=y(u,v), z=z(u,v), (u,v)\in U\subset\mathbb{R}^2,$$ is the image through $f$, respectively through the parameterization, of the Delaunay triangulation or an user defined triangulation of the planar domain $D$, respectively $U$. The Delaunay triangulation of a planar region is defined and illustrated in this Jupyter Notebook. If the planar region $D$ ($U$) is rectangular, then one defines a meshgrid on it, and the points of the grid are the input points for the scipy.spatial.Delaunay function that defines the triangulation of $D$, respectively $U$. Triangulation of the Moebius band The Moebius band is parameterized by: $$\begin{align} x(u,v)&=(1+0.5 v\cos(u/2))\cos(u)\ y(u,v)&=(1+0.5 v\cos(u/2))\sin(u)\quad\quad u\in[0,2\pi],\: v\in[-1,1]\ z(u,v)&=0.5 v\sin(u/2) \end{align} $$ Define a meshgrid on the rectangle $U=[0,2\pi]\times[-1,1]$: End of explanation """ from plotly.graph_objs import * def standard_intensity(x,y,z): return z def plotly_triangular_mesh(x,y,z, faces, intensities=standard_intensity, colorscale="Viridis", showscale=False, reversescale=False, plot_edges=False): #x,y,z lists or np.arrays of vertex coordinates #faces = a numpy array of shape (n_faces, 3) #intensities can be either a function of (x,y,z) or a list of values vertices=np.vstack((x,y,z)).T I,J,K=faces.T if hasattr(intensities, '__call__'): intensity=intensities(x,y,z)#the intensities are computed here via the set function, #that returns the list of vertices intensities elif isinstance(intensities, (list, np.ndarray)): intensity=intensities#intensities are given in a list else: raise ValueError("intensities can be either a function or a list, np.array") mesh=dict(type='mesh3d', x=x, y=y, z=z, colorscale=colorscale, reversescale=reversescale, intensity= intensity, i=I, j=J, k=K, name='', showscale=showscale ) if showscale is True: mesh.update(colorbar=dict(thickness=20, ticklen=4, len=0.75)) if plot_edges is False: # the triangle sides are not plotted return [mesh] else:#plot edges #define the lists Xe, Ye, Ze, of x, y, resp z coordinates of edge end points for each triangle #None separates data corresponding to two consecutive triangles tri_vertices= vertices[faces] Xe=[] Ye=[] Ze=[] for T in tri_vertices: Xe+=[T[k%3][0] for k in range(4)]+[ None] Ye+=[T[k%3][1] for k in range(4)]+[ None] Ze+=[T[k%3][2] for k in range(4)]+[ None] #define the lines to be plotted lines=dict(type='scatter3d', x=Xe, y=Ye, z=Ze, mode='lines', name='', line=dict(color= 'rgb(50,50,50)', width=1.5) ) return [mesh, lines] """ Explanation: tri.simplices is a np.array of integers, of shape (ntri,3), where ntri is the number of triangles generated by scipy.spatial.Delaunay. Each row in this array contains three indices, i, j, k, such that points2D[i,:], points2D[j,:], points2D[k,:] are vertices of a triangle in the Delaunay triangulation of the rectangle $U$. The images of the points2D through the surface parameterization are 3D points. The same simplices define the triangles on the surface. Setting a combination of keys in Mesh3d leads to generating and plotting a tri-surface, in the same way as plot_trisurf in matplotlib or trisurf in Matlab does. We note that Mesh3d with different combination of keys can generate alpha-shapes. To plot the triangles on a surface, we set in Plotly Mesh3d the lists of x, y, respectively z- coordinates of the vertices, and the lists of indices, i, j, k, for x, y, z coordinates of all vertices: Now we define a function that returns data for a Plotly plot of a tri-surface: End of explanation """ pl_RdBu=[[0.0, 'rgb(103, 0, 31)'], [0.1, 'rgb(176, 23, 42)'], [0.2, 'rgb(214, 96, 77)'], [0.3, 'rgb(243, 163, 128)'], [0.4, 'rgb(253, 219, 199)'], [0.5, 'rgb(246, 246, 246)'], [0.6, 'rgb(209, 229, 240)'], [0.7, 'rgb(144, 196, 221)'], [0.8, 'rgb(67, 147, 195)'], [0.9, 'rgb(32, 100, 170)'], [1.0, 'rgb(5, 48, 97)']] data1=plotly_triangular_mesh(x,y,z, tri.simplices, intensities=standard_intensity, colorscale=pl_RdBu, showscale=True, plot_edges=True) """ Explanation: Call this function for data associated to Moebius band: End of explanation """ axis = dict( showbackground=True, backgroundcolor="rgb(230, 230,230)", gridcolor="rgb(255, 255, 255)", zerolinecolor="rgb(255, 255, 255)", ) layout = Layout( title='Moebius band triangulation', width=800, height=800, showlegend=False, scene=Scene(xaxis=XAxis(axis), yaxis=YAxis(axis), zaxis=ZAxis(axis), aspectratio=dict(x=1, y=1, z=0.5 ), ) ) fig1 = Figure(data=data1, layout=layout) py.iplot(fig1, filename='Mobius-band-trisurf') """ Explanation: Set the layout of the plot: End of explanation """ n=12# number of radii h=1.0/(n-1) r = np.linspace(h, 1.0, n) theta= np.linspace(0, 2*np.pi, 36) r,theta=np.meshgrid(r,theta) r=r.flatten() theta=theta.flatten() #Convert polar coordinates to cartesian coordinates (x,y) x=r*np.cos(theta) y=r*np.sin(theta) x=np.append(x, 0)# a trick to include the center of the disk in the set of points. It was avoided # initially when we defined r=np.linspace(h, 1.0, n) y=np.append(y,0) z = np.sin(-x*y) points2D=np.vstack([x,y]).T tri=Delaunay(points2D) """ Explanation: Triangulation of the surface $z=\sin(-xy)$, defined over a disk We consider polar coordinates on the disk, $D(0, 1)$, centered at origin and of radius 1, and define a meshgrid on the set of points $(r, \theta)$, with $r\in[0,1]$ and $\theta\in[0,2\pi]$: End of explanation """ pl_cubehelix=[[0.0, 'rgb(0, 0, 0)'], [0.1, 'rgb(25, 20, 47)'], [0.2, 'rgb(21, 60, 77)'], [0.3, 'rgb(30, 101, 66)'], [0.4, 'rgb(83, 121, 46)'], [0.5, 'rgb(161, 121, 74)'], [0.6, 'rgb(207, 126, 146)'], [0.7, 'rgb(207, 157, 218)'], [0.8, 'rgb(193, 202, 243)'], [0.9, 'rgb(210, 238, 238)'], [1.0, 'rgb(255, 255, 255)']] data2=plotly_triangular_mesh(x,y,z, tri.simplices, intensities=standard_intensity, colorscale=pl_cubehelix, showscale=True, reversescale=False, plot_edges=False) fig2 = Figure(data=data2, layout=layout) fig2['layout'].update(dict(title='Triangulated surface', scene=dict(camera=dict(eye=dict(x=1.75, y=-0.7, z= 0.75) ) ))) py.iplot(fig2, filename='cubehexn') """ Explanation: Plot the surface with a modified layout: End of explanation """ from plyfile import PlyData, PlyElement """ Explanation: Plotting tri-surfaces from data stored in ply-files A PLY (Polygon File Format or Stanford Triangle Format) format is a format for storing graphical objects that are represented by a triangulation of an object, resulted usually from scanning that object. A Ply file contains the coordinates of vertices, the codes for faces (triangles) and other elements, as well as the color for faces or the normal direction to faces. In the following we show how we can read a ply file via the Python package, plyfile. This package can be installed with pip. End of explanation """ def extract_data(plydata): vertices=list(plydata['vertex']) vertices=np.asarray(map(list, vertices)) nr_faces=plydata.elements[1].count faces=np.array([plydata['face'][k][0] for k in range(nr_faces)]) return vertices, faces """ Explanation: Define a function that extract from plydata the vertices and the faces of a triangulated 3D object: End of explanation """ import urllib2 req = urllib2.Request('http://people.sc.fsu.edu/~jburkardt/data/ply/chopper.ply') opener = urllib2.build_opener() f = opener.open(req) plydata = PlyData.read(f) vertices, faces=extract_data(plydata) x, y, z=vertices.T """ Explanation: We choose a ply file from a list provided here. End of explanation """ data3=plotly_triangular_mesh(x,y,z, faces, intensities=standard_intensity, colorscale=pl_RdBu, showscale=True, reversescale=False, plot_edges=True) """ Explanation: Get data for a Plotly plot of the graphical object read from the ply file: End of explanation """ title="Trisurf from a PLY file<br>"+\ "Data Source:<a href='http://people.sc.fsu.edu/~jburkardt/data/ply/airplane.ply'> [1]</a>" noaxis=dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='' ) fig3 = Figure(data=data3, layout=layout) fig3['layout'].update(dict(title=title, width=1000, height=1000, scene=dict(xaxis=noaxis, yaxis=noaxis, zaxis=noaxis, aspectratio=dict(x=1, y=1, z=0.4), camera=dict(eye=dict(x=1.25, y=1.25, z= 1.25) ) ) )) py.iplot(fig3, filename='Chopper-Ply-lines') """ Explanation: Update the layout for this new plot: End of explanation """ from skimage import measure X,Y,Z = np.mgrid[-2:2:40j, -2:2:40j, -2:2:40j] F = X**4 + Y**4 + Z**4 - (X**2+Y**2+Z**2)**2 + 3*(X**2+Y**2+Z**2) - 3 vertices, simplices = measure.marching_cubes_lewiner(F, 0, spacing=(X[1,0, 0]-X[0,0,0], Y[0,1, 0]-Y[0,0,0], Z[0,0, 1]-Z[0,0,0]))[:2] x,y,z = zip(*vertices) pl_amp=[[0.0, 'rgb(241, 236, 236)'], [0.1, 'rgb(229, 207, 200)'], [0.2, 'rgb(219, 177, 163)'], [0.3, 'rgb(211, 148, 127)'], [0.4, 'rgb(201, 119, 91)'], [0.5, 'rgb(191, 88, 58)'], [0.6, 'rgb(179, 55, 38)'], [0.7, 'rgb(157, 24, 38)'], [0.8, 'rgb(126, 13, 41)'], [0.9, 'rgb(92, 14, 32)'], [1.0, 'rgb(60, 9, 17)']] data4=plotly_triangular_mesh(x,y,z,simplices, intensities=standard_intensity, colorscale=pl_amp, showscale=True, reversescale=True, plot_edges=False) fig4 = Figure(data=data4, layout=layout) fig4['layout'].update(dict(title='Isosurface', width=600, height=600, scene=dict(camera=dict(eye=dict(x=1, y=1, z=1) ), aspectratio=dict(x=1, y=1, z=1) ))) py.iplot(fig4,filename='Isosurface') from IPython.core.display import HTML def css_styling(): styles = open("./custom.css", "r").read() return HTML(styles) css_styling() """ Explanation: Plotly plot of an isosurface An isosurface, F(x,y,z) = c, is discretized by a triangular mesh, extracted by the Marching cubes algorithm from a volume given as a (M, N, P) array of doubles. The scikit image function, measure.marching_cubes_lewiner(F, c) returns the vertices and simplices of the triangulated surface. End of explanation """
DiXiT-eu/collatex-tutorial
unit8/unit8-collatex-and-XML/CollateX and XML, Part 2.ipynb
gpl-3.0
from collatex import * from lxml import etree import json,re """ Explanation: CollateX and XML, Part 2 David J. Birnbaum (&#100;&#106;&#98;&#112;&#105;&#116;&#116;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;, http://www.obdurodon.org), 2015-06-29 This example collates a single line of XML from four witnesses. In Part 1 we spelled out the details step by step in a way that would not be used in a real project, but that made it easy to see how each step moves toward the final result. In Part 2 we employ three classes (WitnessSet, Line, Word) to make the code more extensible and adaptable. The sample input is still a single line for four witnesses, given as strings within the Python script. This time, though, the witness identifier (siglum) is given as an attribute on the XML input line. Load libraries. Unchanged from Part 1. End of explanation """ class WitnessSet: def __init__(self,witnessList): self.witnessList = witnessList def generate_json_input(self): json_input = {} witnesses = [] json_input['witnesses'] = witnesses for witness in self.witnessList: line = Line(witness) witnessData = {} witnessData['id'] = line.siglum() witnessTokens = {} witnessData['tokens'] = line.tokens() witnesses.append(witnessData) return json_input """ Explanation: The WitnessSet class represents all of the witnesses being collated. The generate_json_input() method returns a JSON object that is suitable for input into CollateX. At the moment each witness contains just one line (&lt;l&gt; element), so the entire witness is treated as a line. In future parts of this tutorial, the lines will be processed individually, segmenting the collation task into subtasks that collate just one line at a time. End of explanation """ class Line: addWMilestones = etree.XML(""" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="no" encoding="UTF-8" omit-xml-declaration="yes"/> <xsl:template match="*|@*"> <xsl:copy> <xsl:apply-templates select="node() | @*"/> </xsl:copy> </xsl:template> <xsl:template match="/*"> <xsl:copy> <xsl:apply-templates select="@*"/> <!-- insert a <w/> milestone before the first word --> <w/> <xsl:apply-templates/> </xsl:copy> </xsl:template> <!-- convert <add>, <sic>, and <crease> to milestones (and leave them that way) CUSTOMIZE HERE: add other elements that may span multiple word tokens --> <xsl:template match="add | sic | crease "> <xsl:element name="{name()}"> <xsl:attribute name="n">start</xsl:attribute> </xsl:element> <xsl:apply-templates/> <xsl:element name="{name()}"> <xsl:attribute name="n">end</xsl:attribute> </xsl:element> </xsl:template> <xsl:template match="note"/> <xsl:template match="text()"> <xsl:call-template name="whiteSpace"> <xsl:with-param name="input" select="translate(.,'&#x0a;',' ')"/> </xsl:call-template> </xsl:template> <xsl:template name="whiteSpace"> <xsl:param name="input"/> <xsl:choose> <xsl:when test="not(contains($input, ' '))"> <xsl:value-of select="$input"/> </xsl:when> <xsl:when test="starts-with($input,' ')"> <xsl:call-template name="whiteSpace"> <xsl:with-param name="input" select="substring($input,2)"/> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="substring-before($input, ' ')"/> <w/> <xsl:call-template name="whiteSpace"> <xsl:with-param name="input" select="substring-after($input,' ')"/> </xsl:call-template> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> """) transformAddW = etree.XSLT(addWMilestones) xsltWrapW = etree.XML(''' <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="no" omit-xml-declaration="yes"/> <xsl:template match="/*"> <xsl:copy> <xsl:apply-templates select="w"/> </xsl:copy> </xsl:template> <xsl:template match="w"> <!-- faking <xsl:for-each-group> as well as the "<<" and except" operators --> <xsl:variable name="tooFar" select="following-sibling::w[1] | following-sibling::w[1]/following::node()"/> <w> <xsl:copy-of select="following-sibling::node()[count(. | $tooFar) != count($tooFar)]"/> </w> </xsl:template> </xsl:stylesheet> ''') transformWrapW = etree.XSLT(xsltWrapW) def __init__(self,line): self.line = line def siglum(self): return str(etree.XML(self.line).xpath('/l/@wit')[0]) def tokens(self): return [Word(token).createToken() for token in Line.transformWrapW(Line.transformAddW(etree.XML(self.line))).xpath('//w')] """ Explanation: The Line class contains methods applied to individual lines (note that each witness in this part of the tutorial consists of only a single line). The XSLT stylesheets and the functions to use them have been moved into the Line class, since they apply to individual lines. The siglum() method returns the manuscript identifier and the tokens() method returns a list of JSON objects, one for each word token. With a witness that contained more than one line, the siglum would be a property of the witness and the tokens would be a property of each line of the witness. In this part of the tutorial, since each witness has only one line, the siglum is recorded as an attribute of the line, rather than of an XML ancestor that contains all of the lines of the witness. End of explanation """ class Word: unwrapRegex = re.compile('<w>(.*)</w>') stripTagsRegex = re.compile('<.*?>') def __init__(self,word): self.word = word def unwrap(self): return Word.unwrapRegex.match(etree.tostring(self.word,encoding='unicode')).group(1) def normalize(self): return Word.stripTagsRegex.sub('',self.unwrap().lower()) def createToken(self): token = {} token['t'] = self.unwrap() token['n'] = self.normalize() return token """ Explanation: The Word class contains methods that apply to individual words. unwrap() and normalize() are private; they are used by createToken() to return a JSON object with the "t" and "n" properties for a word token. End of explanation """ A = """<l wit='A'><abbrev>Et</abbrev>cil i partent seulement</l>""" B = """<l wit='B'><abbrev>Et</abbrev>cil i p<abbrev>er</abbrev>dent ausem<abbrev>en</abbrev>t</l>""" C = """<l wit='C'><abbrev>Et</abbrev>cil i p<abbrev>ar</abbrev>tent seulema<abbrev>n</abbrev>t</l>""" D = """<l wit='D'>E cil i partent sulement</l>""" witnessSet = WitnessSet([A,B,C,D]) """ Explanation: Create XML data and assign to a witnessSet variable End of explanation """ json_input = witnessSet.generate_json_input() print(json_input) """ Explanation: Generate JSON from the data and examine it End of explanation """ collationText = collate(json_input,output='table',layout='vertical') print(collationText) collationJSON = collate(json_input,output='json') print(collationJSON) collationHTML2 = collate(json_input,output='html2') """ Explanation: Collate and output the results as a plain-text alignment table, as JSON, and as colored HTML End of explanation """
facaiy/book_notes
Reinforcement_Learing_An_Introduction/Temporal_Difference_Learning/note.ipynb
cc0-1.0
Image('./res/fig6_1.png') Image('./res/TD_0.png') """ Explanation: Chapter 6 Temporal-Difference Learning DP, TD, and Monte Carlo methods all use some variation of generalized policy iteration: primarily differences in their approaches to the prediction problem. 6.1 TD Prediction constant-$\alpha$ MC: $V(S_t) \gets V(S_t) + \alpha \underbrace{\left [ G_t - V(S_t) \right ]}{= \sum{k=t}^{T-1} \gamma^{k-1} \theta_k}$ \begin{align} v_\pi(s) &\doteq \mathbb{E}\pi [ G_t \mid S_s = s] \qquad \text{Monte Carlo} \ &= \mathbb{E}\pi [ R_{t+1} + \gamma \color{blue}{v_\pi(S_{t+1})} \mid S_t = s ] \quad \text{DP} \end{align} one-step TD, or TD(0): $V(S_t) \gets V(S_t) + \alpha \left [ \underbrace{R_{t+1} + \gamma \color{blue}{V(S_{t+1})} - V(S_t)}_{\text{TD error: } \theta_t} \right ]$ TD: samples the expected values and uses the current estimate $V$ instead of the true $v_\pi$. End of explanation """ Image('./res/sarsa.png') """ Explanation: 6.2 Advantages of TD Prediction Methods TD: they learn a guess from a guess - they boostrap. advantage: over DP: TD do not require a model of the environment, of its reward and next-state probability distributions. over Monte Carlo: TD are naturally implemented in an online, fully incremental fashion. TD: guarantee convergence. In practice, TD methods have usually been found that converge faster than constant-$\alpha$ MC methods on stochastic tasks. 6.3 Optimality of TD(0) batch updating: updates are made only after processing each complete batch of training data until the value function converges. Batch Monte Carlo methods: always find the estimates that minimize mean-squared error on the training set. Batch TD(0): always find the estimates that would be exactly correct for the maximum-likelihood model of the Markov process. 6.4 Sarsa: On-policy TD Control $Q(S_t, A_t) \gets Q(S_t, A_t) + \alpha \left [ R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}) - Q(S_t,, A_t) \right ]$ End of explanation """ Image('./res/q_learn_off_policy.png') """ Explanation: 6.5 Q-learning: Off-policy TD Control $Q(S_t, A_t) \gets Q(S_t, A_t) + \alpha \left [ R_{t+1} + \gamma \color{blue}{\max_a Q(S_{t+1}, a)} - Q(S_t,, A_t) \right ]$ End of explanation """ Image('./res/double_learn.png') """ Explanation: 6.6 Expected Sarsa use expeteced value, how likely each action is under the current policy. \begin{align} Q(S_t, A_t) & \gets Q(S_t, A_t) + \alpha \left [ R_{t+1} + \gamma \color{blue}{\mathbb{E}[Q(S_{t+1}, A_{t+1}) \mid S_{t+1}]} - Q(S_t,, A_t) \right ] \ & \gets Q(S_t, A_t) + \alpha \left [ R_{t+1} + \gamma \color{blue}{\sum_a \pi(a \mid S_{t+1}) Q(S_{t+1}, a)} - Q(S_t,, A_t) \right ] \end{align} con: additional computational cost. pro: eliminate the variance due to the random seleciton of $A_{t+1}$. 6.7 Maximization Bias and Double Learning maximization bias: + a maximum over estimated values => an estimate of the maximum value => significant positive bias. root of problem: using the same samples (plays) both to determine the maximizing action and to estimate its value. => divide the plays in two sets ($Q_1, Q_2$) and use them to learn two indepedent estimates. (double learning) $Q_1(S_t, A_t) \gets Q_1(S_t, A_t) + \alpha \left [ R_{t+1} + \gamma Q_2 \left( S_{t+1}, \operatorname{argmax}a Q_1(S{t+1}, a) \right) - Q_1(S_t,, A_t) \right ]$ End of explanation """
mne-tools/mne-tools.github.io
0.15/_downloads/plot_mne_inverse_coherence_epochs.ipynb
bsd-3-clause
# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.minimum_norm import (apply_inverse, apply_inverse_epochs, read_inverse_operator) from mne.connectivity import seed_target_indices, spectral_connectivity print(__doc__) """ Explanation: Compute coherence in source space using a MNE inverse solution This example computes the coherence between a seed in the left auditory cortex and the rest of the brain based on single-trial MNE-dSPM inverse solutions. End of explanation """ data_path = sample.data_path() subjects_dir = data_path + '/subjects' fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' fname_raw = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' fname_event = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' label_name_lh = 'Aud-lh' fname_label_lh = data_path + '/MEG/sample/labels/%s.label' % label_name_lh event_id, tmin, tmax = 1, -0.2, 0.5 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) # Load data. inverse_operator = read_inverse_operator(fname_inv) label_lh = mne.read_label(fname_label_lh) raw = mne.io.read_raw_fif(fname_raw) events = mne.read_events(fname_event) # Add a bad channel. raw.info['bads'] += ['MEG 2443'] # pick MEG channels. picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, exclude='bads') # Read epochs. epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=dict(mag=4e-12, grad=4000e-13, eog=150e-6)) """ Explanation: Read the data First we'll read in the sample MEG data that we'll use for computing coherence between channels. We'll convert this into epochs in order to compute the event-related coherence. End of explanation """ snr = 3.0 lambda2 = 1.0 / snr ** 2 evoked = epochs.average() stc = apply_inverse(evoked, inverse_operator, lambda2, method, pick_ori="normal") # Restrict the source estimate to the label in the left auditory cortex. stc_label = stc.in_label(label_lh) # Find number and index of vertex with most power. src_pow = np.sum(stc_label.data ** 2, axis=1) seed_vertno = stc_label.vertices[0][np.argmax(src_pow)] seed_idx = np.searchsorted(stc.vertices[0], seed_vertno) # index in orig stc # Generate index parameter for seed-based connectivity analysis. n_sources = stc.data.shape[0] indices = seed_target_indices([seed_idx], np.arange(n_sources)) """ Explanation: Choose channels for coherence estimation Next we'll calculate our channel sources. Then we'll find the most active vertex in the left auditory cortex, which we will later use as seed for the connectivity computation. End of explanation """ snr = 1.0 # use lower SNR for single epochs lambda2 = 1.0 / snr ** 2 stcs = apply_inverse_epochs(epochs, inverse_operator, lambda2, method, pick_ori="normal", return_generator=True) """ Explanation: Compute the inverse solution for each epoch. By using "return_generator=True" stcs will be a generator object instead of a list. This allows us so to compute the coherence without having to keep all source estimates in memory. End of explanation """ fmin = (8., 13.) fmax = (13., 30.) sfreq = raw.info['sfreq'] # the sampling frequency coh, freqs, times, n_epochs, n_tapers = spectral_connectivity( stcs, method='coh', mode='fourier', indices=indices, sfreq=sfreq, fmin=fmin, fmax=fmax, faverage=True, n_jobs=1) print('Frequencies in Hz over which coherence was averaged for alpha: ') print(freqs[0]) print('Frequencies in Hz over which coherence was averaged for beta: ') print(freqs[1]) """ Explanation: Compute the coherence between sources Now we are ready to compute the coherence in the alpha and beta band. fmin and fmax specify the lower and upper freq. for each band, respectively. To speed things up, we use 2 parallel jobs and use mode='fourier', which uses a FFT with a Hanning window to compute the spectra (instead of a multitaper estimation, which has a lower variance but is slower). By using faverage=True, we directly average the coherence in the alpha and beta band, i.e., we will only get 2 frequency bins. End of explanation """ tmin = np.mean(freqs[0]) tstep = np.mean(freqs[1]) - tmin coh_stc = mne.SourceEstimate(coh, vertices=stc.vertices, tmin=1e-3 * tmin, tstep=1e-3 * tstep, subject='sample') # Now we can visualize the coherence using the plot method. brain = coh_stc.plot('sample', 'inflated', 'both', time_label='Coherence %0.1f Hz', subjects_dir=subjects_dir, clim=dict(kind='value', lims=(0.25, 0.4, 0.65))) brain.show_view('lateral') """ Explanation: Generate coherence sources and plot Finally, we'll generate a SourceEstimate with the coherence. This is simple since we used a single seed. For more than one seed we would have to choose one of the slices within coh. <div class="alert alert-info"><h4>Note</h4><p>We use a hack to save the frequency axis as time.</p></div> Finally, we'll plot this source estimate on the brain. End of explanation """
matt-graham/auxiliary-pm-mcmc
experiment_notebooks/Auxiliary Pseudo-Marginal MCMC - MI u updates and RD-SS theta updates.ipynb
mit
data_dir = os.path.join(os.environ['DATA_DIR'], 'uci') exp_dir = os.path.join(os.environ['EXP_DIR'], 'apm_mcmc') """ Explanation: Construct data and experiments directorys from environment variables End of explanation """ data_set = 'pima' method = 'apm(mi+rdss)' n_chain = 10 chain_offset = 0 seeds = np.random.random_integers(10000, size=n_chain) n_imp_sample = 1 n_sample = 10000 + 500 # 500 'warm-up' updates epsilon = 1e-8 w = 1 max_steps_out = 0 """ Explanation: Specify main run parameters End of explanation """ X = np.genfromtxt(os.path.join(data_dir, data_set + '_X.txt')) y = np.genfromtxt(os.path.join(data_dir, data_set + '_y.txt')) X, X_mn, X_sd = utils.normalise_inputs(X) """ Explanation: Load data and normalise inputs End of explanation """ prior = dict( a_tau = 1., b_tau = 1. / X.shape[1]**0.5, a_sigma = 1.1, b_sigma = 0.1 ) """ Explanation: Specify prior parameters (data dependent so do after data load) End of explanation """ run_params = dict( data_set = data_set, n_data = X.shape[0], n_feature = X.shape[1], method = method, n_imp_sample = n_imp_sample, epsilon = epsilon, prior = prior, w = w, max_steps_out = max_steps_out, n_sample = n_sample ) """ Explanation: Assemble run parameters into dictionary for recording with results End of explanation """ def dir_and_w_sampler(w): d = prng.normal(size=2) d /= d.dot(d)**0.5 return d, w prng = np.random.RandomState() kernel_func = lambda K, X, theta: ( krn.isotropic_squared_exponential_kernel(K, X, theta, epsilon) ) ml_estimator = est.LogMarginalLikelihoodApproxPosteriorISEstimator( X, y, kernel_func, lpa.laplace_approximation) def log_f_estimator(u, theta=None, cached_res=None): log_marg_lik_est, new_cached_res = ml_estimator(u, theta, cached_res) log_prior = ( utils.log_gamma_log_pdf(theta[0], prior['a_sigma'], prior['b_sigma']) + utils.log_gamma_log_pdf(theta[1], prior['a_tau'], prior['b_tau']) ) return log_marg_lik_est + log_prior, new_cached_res sampler = smp.APMMetIndPlusRandDirSliceSampler( log_f_estimator, lambda: prng.normal(size=(y.shape[0], n_imp_sample)), prng, lambda: dir_and_w_sampler(w), max_steps_out) """ Explanation: Create necessary run objects End of explanation """ for c in range(n_chain): try: print('Starting chain {0}...'.format(c + 1)) prng.seed(seeds[c]) theta_init = np.array([ np.log(prng.gamma(prior['a_sigma'], 1. / prior['b_sigma'])), np.log(prng.gamma(prior['a_tau'], 1. / prior['b_tau'])), ]) ml_estimator.reset_cubic_op_count() start_time = time.clock() thetas, n_reject = sampler.get_samples(theta_init, n_sample) comp_time = time.clock() - start_time n_cubic_ops = ml_estimator.n_cubic_ops tag = '{0}_{1}_chain_{2}'.format(data_set, method, c + 1 + chain_offset) print('Completed: u update accept rate {0:.1f}%, time {1}s, # cubic ops {2}' .format((1. - n_reject * 1./ n_sample) * 100., comp_time, n_cubic_ops)) utils.save_run(exp_dir, tag, thetas, n_reject, n_cubic_ops, comp_time, run_params) utils.plot_trace(thetas) plt.show() except Exception as e: print('Exception encountered') print(e.message) print('Skipping to next chain') continue """ Explanation: Run chains, starting from random sample from prior in each and saving results to experiments directory End of explanation """
keylime1/courses_12-752
yingyin2/Variable selection.ipynb
mit
import csv file = open('public_layout.csv','r') reader = csv.reader(file, delimiter=',') fullcsv = list(reader) """ Explanation: Firstly import csv and open the csv file. End of explanation """ dic_1=dict() print(dic_1) for i in range(801): data = np.genfromtxt('recs2009_public.csv',delimiter=',',skip_header=1,usecols=(i,908)) coef = np.corrcoef(data[:,0],data[:,1]) if abs(coef[0][1])>=0.35: dic_1[i]=coef[0][1] print(dic_1) """ Explanation: Create an empty dictionary and for each variable whose absolute value of correlation coefficient with the heating space energy consumption is greater than 0.35 we use the dictionary to store the position of this variable and the correlation coefficient. End of explanation """ import operator sortedDic=sorted(dic_1.items(), key=operator.itemgetter(1)) sortedDic """ Explanation: Sort the dictionary according to their values of correlation coefficient. End of explanation """ variables_chosen=[6, 315, 430, 705] print(sortedDic[-2]) print(sortedDic[8]) print(sortedDic[6]) """ Explanation: I will print the indices and correlation coefficient of variables we will use in our model besides materials. End of explanation """
enbanuel/phys202-2015-work
assignments/assignment10/ODEsEx02.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint from IPython.html.widgets import interact, fixed """ Explanation: Ordinary Differential Equations Exercise 1 Imports End of explanation """ def lorentz_derivs(yvec, t, sigma, rho, beta): """Compute the the derivatives for the Lorentz system at yvec(t).""" # YOUR CODE HERE x = yvec[0] y = yvec[1] z = yvec[2] dx = sigma*(y - x) dy = x*(rho - z) - y dz = x*y - beta*z return np.array([dx, dy, dz]) print(lorentz_derivs(np.array([0.0, 1.0, 0.0]), 1, 1, 1, 1)) assert np.allclose(lorentz_derivs((1,1,1),0, 1.0, 1.0, 2.0),[0.0,-1.0,-1.0]) """ Explanation: Lorenz system The Lorenz system is one of the earliest studied examples of a system of differential equations that exhibits chaotic behavior, such as bifurcations, attractors, and sensitive dependence on initial conditions. The differential equations read: $$ \frac{dx}{dt} = \sigma(y-x) $$ $$ \frac{dy}{dt} = x(\rho-z) - y $$ $$ \frac{dz}{dt} = xy - \beta z $$ The solution vector is $[x(t),y(t),z(t)]$ and $\sigma$, $\rho$, and $\beta$ are parameters that govern the behavior of the solutions. Write a function lorenz_derivs that works with scipy.integrate.odeint and computes the derivatives for this system. End of explanation """ def solve_lorentz(ic, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0): """Solve the Lorenz system for a single initial condition. Parameters ---------- ic : array, list, tuple Initial conditions [x,y,z]. max_time: float The max time to use. Integrate with 250 points per time unit. sigma, rho, beta: float Parameters of the differential equation. Returns ------- soln : np.ndarray The array of the solution. Each row will be the solution vector at that time. t : np.ndarray The array of time points used. """ # YOUR CODE HERE t = np.linspace(0, max_time, 5*max_time) soln = odeint(lorentz_derivs, ic, t, args=(sigma, rho, beta), atol=1e-9, rtol=1e-8) return np.array(soln), np.array(t) print(solve_lorentz(np.array([0.0, 1.0, 0.0]), 2, 1, 1, 1)) assert True # leave this to grade solve_lorenz """ Explanation: Write a function solve_lorenz that solves the Lorenz system above for a particular initial condition $[x(0),y(0),z(0)]$. Your function should return a tuple of the solution array and time array. End of explanation """ N = 5 colors = plt.cm.hot(np.linspace(0,1,N)) for i in range(N): # To use these colors with plt.plot, pass them as the color argument print(colors[i]) def plot_lorentz(N=10, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0): """Plot [x(t),z(t)] for the Lorenz system. Parameters ---------- N : int Number of initial conditions and trajectories to plot. max_time: float Maximum time to use. sigma, rho, beta: float Parameters of the differential equation. """ # YOUR CODE HERE plt.figure(figsize = (15,8)) np.random.seed(1) k= [] for i in range(N): data = (np.random.random(3)-0.5)*30 k.append(solve_lorentz(data, max_time, sigma, rho, beta)) for j in k: x = [p[0] for p in j[0]] z = [p[2] for p in j[0]] color = plt.cm.hot((x[0] + z[0])/60+0.5) plt.scatter(x, z, color = color) plt.xlabel('$x(t)$') plt.ylabel('$z(t)$') plt.title('Lorentz System') # print(plot_lorentz(N=10, max_time=4.0, sigma=10.0, rho=28.0, beta=8.0/3.0)) plot_lorentz() assert True # leave this to grade the plot_lorenz function """ Explanation: Write a function plot_lorentz that: Solves the Lorenz system for N different initial conditions. To generate your initial conditions, draw uniform random samples for x, y and z in the range $[-15,15]$. Call np.random.seed(1) a single time at the top of your function to use the same seed each time. Plot $[x(t),z(t)]$ using a line to show each trajectory. Color each line using the hot colormap from Matplotlib. Label your plot and choose an appropriate x and y limit. The following cell shows how to generate colors that can be used for the lines: End of explanation """ # YOUR CODE HERE interact(plot_lorentz, max_time = [1,10], N = [1,50], sigma=[0.0,50.0], rho=[0.0,50.0], beta=fixed(8/3)); """ Explanation: Use interact to explore your plot_lorenz function with: max_time an integer slider over the interval $[1,10]$. N an integer slider over the interval $[1,50]$. sigma a float slider over the interval $[0.0,50.0]$. rho a float slider over the interval $[0.0,50.0]$. beta fixed at a value of $8/3$. End of explanation """
borja876/Thinkful-DataScience-Borja
Challenge+Boston+marathon.ipynb
mit
#Compare from a silhouette_score perspective kmeans against Spectral Clustering range_n_clusters = np.arange(10)+2 for n_clusters in range_n_clusters: # The silhouette_score gives the average value for all the samples. # This gives a perspective into the density and separation of the formed # clusters # Initialize the clusterer with n_clusters value and a random generator # seed of 10 for reproducibility. spec_clust = SpectralClustering(n_clusters=n_clusters) cluster_labels1 = spec_clust.fit_predict(X_tr_std) silhouette_avg1 = silhouette_score(X_tr_std, cluster_labels1) kmeans = KMeans(n_clusters=n_clusters, init='k-means++', n_init=10).fit(X_tr_std) cluster_labels2 = kmeans.fit_predict(X_tr_std) silhouette_avg2 = silhouette_score(X_tr_std, cluster_labels2) print("For n_clusters =", n_clusters, "av. sil_score for Spec. clust is :", silhouette_avg1, "av. sil_score for kmeans is :",silhouette_avg2 ) """ Explanation: Compare Spectral Clustering against kMeans using Similarity As there is no ground truth, the criteria used to evaluate clusters produced using Spectral and kmeans is the silhouette coefficient. From the results obtained, it can be appreaciated that Spectral Clustering requires 6 clusters to have the silhouette score similar to the one obtained with 3 clusters with kmeans. End of explanation """ #Use the elbow method to determine the number of clusters # k-means determine k distortions = [] K = range(1,10) for k in K: kmeanModel = KMeans(n_clusters=k).fit(X_tr) kmeanModel.fit(X_tr) distortions.append(sum(np.min(cdist(X_tr, kmeanModel.cluster_centers_, 'euclidean'), axis=1)) / X_tr.shape[0]) # Plot the elbow plt.plot(K, distortions, 'bx-') plt.xlabel('k') plt.ylabel('Distortion') plt.title('The Elbow Method showing the optimal k') plt.show() """ Explanation: the optimal number of kmeans will be determined using the elbow method. Once the kmeans number of clusters is set, the number of clusters using spectral clustering will be used so that it equals the silhouette score obtained in the first case. K-Means End of explanation """ #Evaluate the best number of clusters for i in range(1,10): km = KMeans(n_clusters=i, init='k-means++', n_init=10).fit(X_tr_std) print (i, km.inertia_) #Cluster the data kmeans = KMeans(n_clusters=3, init='k-means++', n_init=10).fit(X_tr_std) labels = kmeans.labels_ #Glue back to original data X_tr['clusters'] = labels X_tr['Gender'] = boston_marathon_scores.gender X_tr['Overall'] = boston_marathon_scores.overall #Add the column into our list clmns.extend(['clusters','Gender','Overall']) #Lets analyze the clusters pd.DataFrame(X_tr.groupby(['clusters']).mean()) clusters_summary = X_tr.groupby(['clusters']).describe() clusters_summary_transposed = clusters_summary.transpose() clusters_summary_transposed # Reduce it to two components. X_pca = PCA(2).fit_transform(X_tr_std) # Calculate predicted values. y_pred = KMeans(n_clusters=3, random_state=42).fit_predict(X_pca) # Plot the solution. plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_pred) plt.show() Graph_kmeans_official = pd.pivot_table(X_tr, 'official', ['clusters', 'gender']) Graph_kmeans_pace = pd.pivot_table(X_tr, 'pace', ['clusters', 'gender']) Graph_kmeans_age = pd.pivot_table(X_tr, 'age', ['clusters', 'gender']) print(Graph_kmeans_official, Graph_kmeans_pace, Graph_kmeans_age) """ Explanation: The elbow method shows that the optimal number of clusters to be used in the kmeans method is 3, considering the euclidean distance between cluster centers. From an analytical perspective, the inertia functions shows the same results: 3 clusters were the difference between the results obtained by the inertia function are smaller when shifting from 3 to 4 clusters. End of explanation """ # We know we're looking for 6 clusters from the comparison with the kmeans. n_clusters=6 # Declare and fit the model. sc = SpectralClustering(n_clusters=n_clusters).fit(X_tr_std) # Extract cluster assignments for each data point. labels = sc.labels_ #Glue back to original data X_tr['clusters'] = labels X_tr['Gender'] = boston_marathon_scores.gender X_tr['Overall'] = boston_marathon_scores.overall #Add the column into our list clmns.extend(['clusters','Gender','Overall']) #Lets analyze the clusters pd.DataFrame(X_tr.groupby(['clusters']).mean()) clusters_summary = X_tr.groupby(['clusters']).describe() clusters_summary_transposed = clusters_summary.transpose() clusters_summary_transposed # Reduce it to two components. X_pca = PCA(2).fit_transform(X_tr_std) # Calculate predicted values. y_pred = SpectralClustering(n_clusters=3).fit_predict(X_pca) # Plot the solution. plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_pred) plt.show() """ Explanation: Spectral Clustering End of explanation """ # Here we set the bandwidth. This function automatically derives a bandwidth # number based on an inspection of the distances among points in the data. bandwidth = estimate_bandwidth(X_tr_std, quantile=0.9) # Declare and fit the model. ms = MeanShift(bandwidth=bandwidth, bin_seeding=True).fit(X_tr_std) # Extract cluster assignments for each data point. labels = ms.labels_ # Coordinates of the cluster centers. cluster_centers = ms.cluster_centers_ # Count our clusters. n_clusters_ = len(np.unique(labels)) #Glue back to original data X_tr['clusters'] = labels X_tr['Gender'] = boston_marathon_scores.gender X_tr['Overall'] = boston_marathon_scores.overall #Add the column into our list clmns.extend(['clusters','Gender','Overall']) #Lets analyze the clusters print("Number of estimated clusters: {}".format(n_clusters_)) pd.DataFrame(X_tr.groupby(['clusters']).mean()) clusters_summary = X_tr.groupby(['clusters']).describe() clusters_summary_transposed = clusters_summary.transpose() clusters_summary_transposed # Reduce it to two components. X_pca = PCA(2).fit_transform(X_tr_std) # Calculate predicted values. bandwidth = estimate_bandwidth(X_tr_std, quantile=0.9) y_pred = MeanShift(bandwidth=bandwidth, bin_seeding=True).fit_predict(X_pca) # Plot the solution. plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y_pred) plt.show() # Declare the model and fit it in one statement. # Note that you can provide arguments to the model, but we didn't. af = AffinityPropagation().fit(X_tr_std) print('Done') # Pull the number of clusters and cluster assignments for each data point. cluster_centers_indices = af.cluster_centers_indices_ n_clusters_ = len(cluster_centers_indices) labels = af.labels_ #Glue back to original data X_tr['clusters'] = labels X_tr['Gender'] = boston_marathon_scores.gender X_tr['Overall'] = boston_marathon_scores.overall #Add the column into our list clmns.extend(['clusters','Gender','Overall']) #Lets analyze the clusters print("Number of estimated clusters: {}".format(n_clusters_)) pd.DataFrame(X_tr.groupby(['clusters']).mean()) clusters_summary = X_tr.groupby(['clusters']).describe() clusters_summary_transposed = clusters_summary.transpose() clusters_summary_transposed """ Explanation: Mean Shift End of explanation """
tommyod/abelian
docs/notebooks/functions.ipynb
gpl-3.0
# Imports from abelian from abelian import LCA, HomLCA, LCAFunc # Other imports import math import matplotlib.pyplot as plt from IPython.display import display, Math def show(arg): return display(Math(arg.to_latex())) """ Explanation: Tutorial: Functions on LCAs This is an interactive tutorial written with real code. We start by setting up $\LaTeX$ printing, and importing the classes LCA, HomLCA and LCAFunc. End of explanation """ def gaussian(vector_arg, k = 0.1): return math.exp(-sum(i**2 for i in vector_arg)*k) # Gaussian function on Z Z = LCA([0]) gauss_on_Z = LCAFunc(gaussian, domain = Z) print(gauss_on_Z) # Printing show(gauss_on_Z) # LaTeX output # Gaussian function on T T = LCA([1], [False]) gauss_on_T = LCAFunc(gaussian, domain = T) show(gauss_on_T) # LaTeX output """ Explanation: Initializing a new function There are two ways to create a function $f: G \to \mathbb{C}$: On general LCAs $G$, the function is represented by an analytical expression. If $G = \mathbb{Z}_{\mathbf{p}}$ with $p_i \geq 1$ for every $i$ ($G$ is a direct sum of discrete groups with finite period), a table of values (multidimensional array) can also be used. With an analytical representation If the representation of the function is given by an analytical expression, initialization is simple. Below we define a Gaussian function on $\mathbb{Z}$, and one on $T$. End of explanation """ # Create a table of values table_data = [[1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]] # Create a domain matching the table domain = LCA([3, 5]) table_func = LCAFunc(table_data, domain) show(table_func) print(table_func([1, 1])) # [1, 1] maps to 3 """ Explanation: Notice how the print built-in and the to_latex() method will show human-readable output. With a table of values Functions on $\mathbb{Z}_\mathbf{p}$ can be defined using a table of values, if $p_i \geq 1$ for every $p_i \in \mathbf{p}$. End of explanation """ # An element in Z element = [0] # Evaluate the function gauss_on_Z(element) """ Explanation: Function evaluation A function $f \in \mathbb{C}^G$ is callable. To call (i.e. evaluate) a function, pass a group element. End of explanation """ # Create a list of sample points [-6, ..., 6] sample_points = [[i] for i in range(-6, 7)] # Sample the function, returns a list of values sampled_func = gauss_on_Z.sample(sample_points) # Plot the result of sampling the function plt.figure(figsize = (8, 3)) plt.title('Gaussian function on $\mathbb{Z}$') plt.plot(sample_points, sampled_func, '-o') plt.grid(True) plt.show() """ Explanation: The sample() method can be used to sample a function on a list of group elements in the domain. End of explanation """ # The group element to shift by shift_by = [3] # Shift the function shifted_gauss = gauss_on_Z.shift(shift_by) # Create sample poits and sample sample_points = [[i] for i in range(-6, 7)] sampled1 = gauss_on_Z.sample(sample_points) sampled2 = shifted_gauss.sample(sample_points) # Create a plot plt.figure(figsize = (8, 3)) ttl = 'Gaussians on $\mathbb{Z}$, one is shifted' plt.title(ttl) plt.plot(sample_points, sampled1, '-o') plt.plot(sample_points, sampled2, '-o') plt.grid(True) plt.show() """ Explanation: Shifts Let $f: G \to \mathbb{C}$ be a function. The shift operator (or translation operator) $S_{h}$ is defined as $$S_{h}[f(g)] = f(g - h).$$ The shift operator shifts $f(g)$ by $h$, where $h, g \in G$. The shift operator is implemented as a method called shift. End of explanation """ def linear(arg): return sum(arg) # The original function f = LCAFunc(linear, LCA([10])) show(f) # A homomorphism phi phi = HomLCA([2], target = [10]) show(phi) # The pullback of f along phi g = f.pullback(phi) show(g) """ Explanation: Pullbacks Let $\phi: G \to H$ be a homomorphism and let $f:H \to \mathbb{C}$ be a function. The pullback of $f$ along $\phi$, denoted $\phi^*(f)$, is defined as $$\phi^*(f) := f \circ \phi.$$ The pullback "moves" the domain of the function $f$ to $G$, i.e. $\phi^*(f) : G \to \mathbb{C}$. The pullback is of f is calculated using the pullback method, as shown below. End of explanation """ # Sample the functions and plot them sample_points = [[i] for i in range(-5, 15)] f_sampled = f.sample(sample_points) g_sampled = g.sample(sample_points) # Plot the original function and the pullback plt.figure(figsize = (8, 3)) plt.title('Linear functions') label = '$f \in \mathbb{Z}_{10}$' plt.plot(sample_points, f_sampled, '-o', label = label) label = '$g \circ \phi \in \mathbb{Z}$' plt.plot(sample_points, g_sampled, '-o', label = label) plt.grid(True) plt.legend(loc = 'best') plt.show() """ Explanation: We now sample the functions and plot them. End of explanation """ # We create a function on Z and plot it def gaussian(arg, k = 0.05): """ A gaussian function. """ return math.exp(-sum(i**2 for i in arg)*k) # Create gaussian on Z, shift it by 5 gauss_on_Z = LCAFunc(gaussian, LCA([0])) gauss_on_Z = gauss_on_Z.shift([5]) # Sample points and sampled function s_points = [[i] for i in range(-5, 15)] f_sampled = gauss_on_Z.sample(s_points) # Plot it plt.figure(figsize = (8, 3)) plt.title('A gaussian function on $\mathbb{Z}$') plt.plot(s_points, f_sampled, '-o') plt.grid(True) plt.show() # Use a pushforward to periodize the function phi = HomLCA([1], target = [10]) show(phi) """ Explanation: Pushforwards Let $\phi: G \to H$ be a epimorphism and let $f:G \to \mathbb{C}$ be a function. The pushforward of $f$ along $\phi$, denoted $\phi_*(f)$, is defined as $$(\phi_*(f))(g) := \sum_{k \in \operatorname{ker}\phi} f(k + h), \quad \phi(g) = h$$ The pullback "moves" the domain of the function $f$ to $H$, i.e. $\phi_*(f) : H \to \mathbb{C}$. First a solution is obtained, then we sum over the kernel. Since such a sum may contain an infinite number of terms, we bound it using a norm. Below is an example where we: Define a Gaussian $f(x) = \exp(-kx^2)$ on $\mathbb{Z}$ Use pushforward to "move" it with $\phi(g) = g \in \operatorname{Hom}(\mathbb{Z}, \mathbb{Z}_{10})$ End of explanation """ terms = 1 # Pushforward of the function along phi gauss_on_Z_10 = gauss_on_Z.pushforward(phi, terms) # Sample the functions and plot them pushforward_sampled = gauss_on_Z_10.sample(sample_points) plt.figure(figsize = (8, 3)) label = 'A gaussian function on $\mathbb{Z}$ and \ pushforward to $\mathbb{Z}_{10}$ with few terms in the sum' plt.title(label) plt.plot(s_points, f_sampled, '-o', label ='Original') plt.plot(s_points, pushforward_sampled, '-o', label ='Pushforward') plt.legend(loc = 'best') plt.grid(True) plt.show() """ Explanation: First we do a pushforward with only one term. Not enough terms are present in the sum to capture what the pushforward would look like if the sum went to infinity. End of explanation """ terms = 9 gauss_on_Z_10 = gauss_on_Z.pushforward(phi, terms) # Sample the functions and plot them pushforward_sampled = gauss_on_Z_10.sample(sample_points) plt.figure(figsize = (8, 3)) plt.title('A gaussian function on $\mathbb{Z}$ and \ pushforward to $\mathbb{Z}_{10}$ with enough terms') plt.plot(s_points, f_sampled, '-o', label ='Original') plt.plot(s_points, pushforward_sampled, '-o', label ='Pushforward') plt.legend(loc = 'best') plt.grid(True) plt.show() """ Explanation: Next we do a pushforward with more terms in the sum, this captures what the pushforward would look like if the sum went to infinity. End of explanation """
planet-os/notebooks
api-examples/gfs-api.ipynb
mit
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import dateutil.parser import datetime from urllib.request import urlopen, Request import simplejson as json """ Explanation: <h1>Using the Planet OS API to Produce Weather Forecast Graphs</h1> Note: this notebook requires python3. This notebook is an introduction to the PlanetOS API data format using the GFS Global Forecast dataset. API documentation is available at http://docs.planetos.com. If you have questions or comments, join the Planet OS Slack community to chat with our development team. For general information on usage of IPython/Jupyter and Matplotlib, please refer to their corresponding documentation. https://ipython.org/ and http://matplotlib.org/ End of explanation """ longitude = 24.+36./60 latitude = 59+24./60 apikey = open('APIKEY').readlines()[0].strip() #'<YOUR API KEY HERE>' API_url = "http://api.planetos.com/v1/datasets/noaa_gfs_global_sflux_0.12d/point?lon={0}&lat={1}&count=5&verbose=true&apikey={2}".format(longitude,latitude,apikey) request = Request(API_url) response = urlopen(request) API_data = json.loads(response.read()) """ Explanation: <h2>GFS global weather forecast model</h2> GFS is a well known and widely used weather forecast model, developed and used operationally by NCEP (http://www.emc.ncep.noaa.gov/). This model outputs a 15 day global weather forecast on a 12 degree grid. Let's initialize point coordinates longitude, latitude and make short query (count=10) to get some data. Important! You'll need to replace apikey below with your actual Planet OS API key, which you'll find on the Planet OS account settings page. End of explanation """ print("{0:<50} {1}".format("Variable","Context")) print() for k,v in set([(j,i['context']) for i in API_data['entries'] for j in i['data'].keys() if 'wind' in j.lower()]): print("{0:<50} {1}".format(k,v)) """ Explanation: Let's investigate what we received. API response is divided into entries, stats and metadata, where stats gives info about available data extent, metadata for gives full information about variables, and entries has actual data. Data in the entries section is divided into different messages, where each has axes which describes time and location of data; context which describes the coordinate types; and data which gives the actual variables with corresponding values. To efficiently use the data, we loop through messages and collect data to separate variables. But first, let's try filtering data by variable type (precipitation, temperature, etc.). For this, list all related variables and their context. Note that not all variables are available for all timesteps! End of explanation """ time_axes = [] time_axes_precipitation = [] time_axes_wind = [] surface_temperature = [] air2m_temperature = [] precipitation_rate = [] wind_speed = [] for i in API_data['entries']: #print(i['axes']['time']) if i['context'] == 'reftime_time_lat_lon': surface_temperature.append(i['data']['Temperature_surface']) time_axes.append(dateutil.parser.parse(i['axes']['time'])) if i['context'] == 'reftime_time1_lat_lon': if 'Precipitation_rate_surface_3_Hour_Average' in i['data']: precipitation_rate.append(i['data']['Precipitation_rate_surface_3_Hour_Average']*3*3600) time_axes_precipitation.append(dateutil.parser.parse(i['axes']['time'])) if i['context'] == 'reftime_time_height_above_ground_lat_lon': air2m_temperature.append(i['data']['Temperature_height_above_ground']) if i['context'] == 'reftime_time_height_above_ground1_lat_lon': wind_speed.append(np.sqrt(i['data']['u-component_of_wind_height_above_ground']**2+i['data']['v-component_of_wind_height_above_ground']**2)) time_axes_wind.append(dateutil.parser.parse(i['axes']['time'])) time_axes_precipitation = np.array(time_axes_precipitation) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(time_axes,surface_temperature,color='k',label='Surface temperature') ax.plot(time_axes,air2m_temperature,color='r',label='2m temperature') ax_r = ax.twinx() ax_r.bar(time_axes_precipitation-datetime.timedelta(seconds=1800),precipitation_rate,width=0.1,alpha=0.4) fig.autofmt_xdate() plt.show() """ Explanation: Next, select data for time and data axes. As we do not necessarily know what data is available at what timestep, make a separate time variable for each data variable. For easier plotting and analysis, convert the time string to datetime. End of explanation """ #API_url = "http://api.planetos.com/v1/datasets/noaa_gfs_global_sflux_0.12d/point?lon={0}&lat={1}&count=1000&apikey={2}&contexts=reftime_time_lat_lon,reftime_time_height_above_ground_lat_lon,reftime_time1_lat_lon".format(longitude,latitude,apikey) API_url = "http://api.planetos.com/v1/datasets/noaa_gfs_global_sflux_0.12d/point?lon={0}&lat={1}&count=1000&apikey={2}&var=Temperature_surface,Temperature_height_above_ground,Downward_Short-Wave_Radiation_Flux_surface_3_Hour_Average,Precipitation_rate_surface_3_Hour_Average".format(longitude,latitude,apikey) request2 = Request(API_url) response2 = urlopen(request2) API_data2 = json.loads(response2.read()) """ Explanation: We could improve this plot by extending the time axes. To do this, increase the count parameter in the API call. Also note that only three contexts are needed for the data of interest. If we explicitly request those contexts and skip unnecessary ones, we can improve the API response time. Or we can just request needed variables, it will be even faster. Note: Be careful with reference times, because in some cases two reference times may be available! End of explanation """ reftimes = set() for i in API_data2['entries']: reftimes.update([i['axes']['reftime']]) reftimes=list(reftimes) reftimes """ Explanation: Let's find the available reference times in the response... End of explanation """ if len(reftimes)>1: reftime = reftimes[0] if dateutil.parser.parse(reftimes[0])<dateutil.parser.parse(reftimes[1]) else reftimes[1] else: reftime = reftimes[0] """ Explanation: We use the earlier reftime in this example, but a later reftime may provide a more recent forecast. End of explanation """ time_2mt = [] time_surft = [] time_precipitation = [] time_surfrad = [] surface_temperature = [] air2m_temperature = [] precipitation_rate = [] surfrad = [] for i in API_data2['entries']: #print(i['context']) if i['context'] == 'reftime_time_lat_lon' and i['axes']['reftime']==reftime: surface_temperature.append(i['data']['Temperature_surface']-273.15) time_surft.append(dateutil.parser.parse(i['axes']['time'])) if i['context'] == 'reftime_time_height_above_ground_lat_lon' and i['axes']['reftime']==reftime: if 'Temperature_height_above_ground' in i['data']: air2m_temperature.append(i['data']['Temperature_height_above_ground']-273.15) time_2mt.append(dateutil.parser.parse(i['axes']['time'])) if i['context'] == 'reftime_time1_lat_lon' and i['axes']['reftime'] == reftime: if 'Downward_Short-Wave_Radiation_Flux_surface_3_Hour_Average' in i['data']: surfrad.append(i['data']['Downward_Short-Wave_Radiation_Flux_surface_3_Hour_Average']) time_surfrad.append(dateutil.parser.parse(i['axes']['time'])) precipitation_rate.append(i['data']['Precipitation_rate_surface_3_Hour_Average']*3*3600) time_precipitation.append(dateutil.parser.parse(i['axes']['time'])) time_precipitation = np.array(time_precipitation) surfrad=np.array(surfrad) fig = plt.figure(figsize=(15,10)) ax = fig.add_subplot(111) plt.plot(time_surft,surface_temperature,color='k',label='Surface temperature') plt.plot(time_2mt,air2m_temperature,color='r',label='2m temperature') lg = plt.legend(framealpha=0.2) ax.set_ylabel('Temperature, Celsius') ax_r = ax.twinx() ax_r.bar(time_precipitation-datetime.timedelta(seconds=1800),precipitation_rate,width=0.1,alpha=0.4,label='precipitation') ax_r.fill_between(time_surfrad,surfrad/np.amax(surfrad)*np.amax(precipitation_rate),color='gray',alpha=0.1,label='surface radiation') ax_r.set_ylabel('Precipitation, mm 3hr') lg.get_frame().set_alpha(0.5) fig.autofmt_xdate() """ Explanation: Now create a new plot with the longer time scale and one more variable... End of explanation """
PMEAL/OpenPNM
examples/simulations/steady_state/fickian_diffusion_and_tortuosity.ipynb
mit
import numpy as np import openpnm as op %config InlineBackend.figure_formats = ['svg'] import matplotlib.pyplot as plt %matplotlib inline np.random.seed(10) ws = op.Workspace() ws.settings["loglevel"] = 40 np.set_printoptions(precision=5) """ Explanation: Fickian Diffusion and Tortuosity In this example, we will learn how to perform Fickian diffusion on a Cubic network. The algorithm works fine with every other network type, but for now we want to keep it simple. Refere to Tutorials > Network for more details on different network types. End of explanation """ shape = [1, 10, 10] spacing = 1e-5 net = op.network.Cubic(shape=shape, spacing=spacing) """ Explanation: Generating network First, we need to generate a Cubic network. For now, we stick to a 2d network, but you might as well try it in 3d! End of explanation """ geom = op.geometry.SpheresAndCylinders(network=net, pores=net.Ps, throats=net.Ts) """ Explanation: Adding geometry Next, we need to add a geometry to the generated network. A geometry contains information about size of the pores/throats in a network. OpenPNM has tons of prebuilt geometries that represent the microstructure of different materials such as Toray090 carbon papers, sand stone, electrospun fibers, etc. For now, we'll stick to a simple geometry called SpheresAndCylinders that assigns random values to pore/throat diameters. End of explanation """ air = op.phase.Air(network=net) """ Explanation: Adding phase Next, we need to add a phase to our simulation. A phase object(s) contain(s) thermophysical information about the working fluid(s) in the simulation. OpenPNM has tons of prebuilt phases as well! For this simulation, we use air as our working fluid. End of explanation """ phys_air = op.physics.Standard(network=net, phase=air, geometry=geom) """ Explanation: Adding physics Finally, we need to add a physics. A physics object contains information about the working fluid in the simulation that depend on the geometry of the network. A good example is diffusive conductance, which not only depends on the thermophysical properties of the working fluid, but also depends on the geometry of pores/throats. OpenPNM includes a pre-defined physics class called Standard which as the name suggests contains all the standard pore-scale models to get you going: End of explanation """ fd = op.algorithms.FickianDiffusion(network=net, phase=air) """ Explanation: Performing Fickian diffusion Now that everything's set up, it's time to perform our Fickian diffusion simulation. For this purpose, we need to add the FickianDiffusion algorithm to our simulation. Here's how we do it: End of explanation """ inlet = net.pores('front') outlet = net.pores('back') C_in = 1.0 C_out = 0.0 fd.set_value_BC(pores=inlet, values=C_in) fd.set_value_BC(pores=outlet, values=C_out) """ Explanation: Note that network and phase are required parameters for pretty much every algorithm we add, since we need to specify on which network and for which phase we want to run the algorithm. Adding boundary conditions Next, we need to add some boundary conditions to the simulation. By default, OpenPNM assumes zero flux for the boundary pores. End of explanation """ fd.run() """ Explanation: set_value_BC applies the so-called "Dirichlet" boundary condition to the specified pores. Note that unless you want to apply a single value to all of the specified pores (like we just did), you must pass a list (or ndarray) as the values parameter. Running the algorithm Now, it's time to run the algorithm. This is done by calling the run method attached to the algorithm object. End of explanation """ print(fd.settings) """ Explanation: Post processing When an algorithm is successfully run, the results are attached to the same object. To access the results, you need to know the quantity for which the algorithm was solving. For instance, FickianDiffusion solves for the quantity pore.concentration, which is somewhat intuitive. However, if you ever forget it, or wanted to manually check the quantity, you can take a look at the algorithm settings: End of explanation """ c = fd['pore.concentration'] r = fd.rate(throats=net.Ts, mode='single') d = net['pore.diameter'] fig, ax = plt.subplots(figsize=[4, 4]) op.topotools.plot_coordinates(network=net, color_by=c, size_by=d, markersize=400, ax=ax) op.topotools.plot_connections(network=net, color_by=r, linewidth=3, ax=ax) _ = plt.axis('off') """ Explanation: Visualizing Now that we know the quantity for which FickianDiffusion was solved, let's take a look at the results: End of explanation """ rate_inlet = fd.rate(pores=inlet)[0] print(f'Mass flow rate from inlet: {rate_inlet:.5e} mol/s') """ Explanation: Calculating flux You might as well be interested in calculating the mass flux from a boundary! This is easily done in OpenPNM via calling the rate method attached to the algorithm. Let's see how it works: End of explanation """ A = (shape[0] * shape[1])*(spacing**2) L = shape[2]*spacing D_eff = rate_inlet * L / (A * (C_in - C_out)) print("{0:.6E}".format(D_eff)) """ Explanation: We can determine the effective diffusivity of the network by solving Fick's law: $$ D_{eff} = \frac{N_A L}{ A \Delta C} $$ End of explanation """ D_AB = air['pore.diffusivity'][0] F = D_AB / D_eff print('The formation factor is: ', "{0:.6E}".format(F)) """ Explanation: And the formation factor can be found since the diffusion coefficient of open air is known: $$ F = \frac{D_{AB}}{D_{eff}} $$ End of explanation """ V_p = geom['pore.volume'].sum() V_t = geom['throat.volume'].sum() V_bulk = np.prod(shape)*(spacing**3) e = (V_p + V_t) / V_bulk print('The porosity is: ', "{0:.6E}".format(e)) tau = e * D_AB / D_eff print('The tortuosity is:', "{0:.6E}".format(tau)) """ Explanation: The tortuosity is defined as follows: $$ \frac{D_{eff}}{D_{AB}} = \frac{\varepsilon}{\tau} \rightarrow \tau = \varepsilon \frac{ D_{AB}}{D_{eff}} $$ Note that finding the tortuosity requires knowing the porosity, which is annoyingly difficult to calculate accurately, so here we will just gloss over the details. End of explanation """