markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Find points inside a solid
# selecting all inside the solid # This two methods are equivelent but test=4 also works with open surfaces inside,p=pygslib.vtktools.pointquering(mycube, azm=0, dip=0, x=x, y=y, z=z, test=1) inside1,p=pygslib.vtktools.pointquering(mycube, azm=0, dip=0, x=x, y=y, z=z, test=4) err=inside==inside1 #print inside, tuple(...
pygslib/Ipython_templates/broken/vtk_tools.ipynb
opengeostat/pygslib
mit
Find points over a surface
# selecting all over a solid (test = 2) inside,p=pygslib.vtktools.pointquering(mycube, azm=0, dip=0, x=x, y=y, z=z, test=2) # here we prepare to plot the solid, the x,y,z indicator and we also # plot the line (direction) used to ray trace # convert the data in the STL file into a renderer and then we plot it render...
pygslib/Ipython_templates/broken/vtk_tools.ipynb
opengeostat/pygslib
mit
Find points below a surface
# selecting all over a solid (test = 2) inside,p=pygslib.vtktools.pointquering(mycube, azm=0, dip=0, x=x, y=y, z=z, test=3) # here we prepare to plot the solid, the x,y,z indicator and we also # plot the line (direction) used to ray trace # convert the data in the STL file into a renderer and then we plot it render...
pygslib/Ipython_templates/broken/vtk_tools.ipynb
opengeostat/pygslib
mit
Export points to a VTK file
data = {'inside': inside} pygslib.vtktools.points2vtkfile('points', x,y,z, data)
pygslib/Ipython_templates/broken/vtk_tools.ipynb
opengeostat/pygslib
mit
Try out a simple reaction to link two SMILES strings
# Test by linking two molecules - anything with a C or O followed by a B can react with a C or O followed by an F to form # a bond betwen the two C or O atoms, dropping the B or F. libgen = oechem.OELibraryGen("[C,O:1][B:2].[C,O:3][F:4]>>[C,O:1][C,O:3]") mol = oechem.OEGraphMol() oechem.OESmilesToMol(mol, 'COCCB') l...
examples/substructure_linking.ipynb
bmanubay/open-forcefield-tools
mit
Proceed to library generation First, build some sets of molecules to link, capped by our "reactant" groups
# Build two small libraries of molecules for linking # Build a first set of molecules import itertools smileslist1 = [] #Take all two-item combinations of entries in the list for item in itertools.permutations(['C','O','c1ccccc1','CC', 'COC', 'CCOC', 'CCCOC', 'C1CC1', 'C1CCC1', 'C1CCCC1', 'C1CCCCC1','C1OCOCC1'], 2): ...
examples/substructure_linking.ipynb
bmanubay/open-forcefield-tools
mit
Now, generate our library
# Build overall set of reactants libgen = oechem.OELibraryGen("[C,O:1][B:2].[C,O:3][F:4]>>[C,O:1][C,O:3]") mol = oechem.OEGraphMol() for idx, smi in enumerate(smileslist1_rxn): oechem.OESmilesToMol(mol, smi) libgen.AddStartingMaterial(mol, 0) mol.Clear() for idx, smi in enumerate(smileslist2_rxn): oech...
examples/substructure_linking.ipynb
bmanubay/open-forcefield-tools
mit
Generate a conformer for each and write out
omega = oeomega.OEOmega() omega.SetMaxConfs(1) omega.SetStrictStereo(False) # First do just the first 10 molecules #products = products[0:10] ofs = oechem.oemolostream('linked_substructures.oeb') for oemol in products: omega(oemol) oechem.OETriposAtomNames(mol) oechem.OEWriteMolecule(ofs, oemol) ofs.close()...
examples/substructure_linking.ipynb
bmanubay/open-forcefield-tools
mit
Restart the Notebook kernel to use the SDK packages
from IPython.display import display_html display_html("<script>Jupyter.notebook.kernel.restart()</script>",raw=True)
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Import required packages
import kfp import kfp.dsl as dsl from kfp import components from kubeflow.katib import ApiClient from kubeflow.katib import V1beta1ExperimentSpec from kubeflow.katib import V1beta1AlgorithmSpec from kubeflow.katib import V1beta1EarlyStoppingSpec from kubeflow.katib import V1beta1EarlyStoppingSetting from kubeflow.kati...
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Define an Experiment You have to create an Experiment object before deploying it. This Experiment is similar to this YAML.
# Experiment name and namespace. experiment_name = "median-stop" # for multi user deployment, please specify your own namespace instead of "anonymous" experiment_namespace = "anonymous" # Trial count specification. max_trial_count = 18 max_failed_trial_count = 3 parallel_trial_count = 2 # Objective specification. obj...
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Define a Trial template In this example, the Trial's Worker is the Kubernetes Job.
# JSON template specification for the Trial's Worker Kubernetes Job. trial_spec={ "apiVersion": "batch/v1", "kind": "Job", "spec": { "template": { "metadata": { "annotations": { "sidecar.istio.io/inject": "false" } }, ...
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Define an Experiment specification Create an Experiment specification from the above parameters.
experiment_spec=V1beta1ExperimentSpec( max_trial_count=max_trial_count, max_failed_trial_count=max_failed_trial_count, parallel_trial_count=parallel_trial_count, objective=objective, algorithm=algorithm, early_stopping=early_stopping, parameters=parameters, trial_template=trial_template ...
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Create a Pipeline using Katib component The best hyperparameters are printed after Experiment is finished. The Experiment is not deleted after the Pipeline is finished.
# Get the Katib launcher. katib_experiment_launcher_op = components.load_component_from_url( "https://raw.githubusercontent.com/kubeflow/pipelines/master/components/kubeflow/katib-launcher/component.yaml") PRINT_STR = """ name: print description: print msg inputs: - {name: message, type: JsonObject} implementati...
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Run the Pipeline You can check the Katib Experiment info in the Katib UI. If you run this in a multi-user deployment, you need to follow the instructions here: https://github.com/kubeflow/kfp-tekton/tree/master/guides/kfp-user-guide#2-upload-pipelines-using-the-kfp_tektontektonclient-in-python Check the multi tenant se...
from kfp_tekton._client import TektonClient # Example code for multi user deployment: # TektonClient( # host='http://<Kubeflow_public_endpoint_URL>/pipeline', # cookies='authservice_session=xxxxxxx' # ).create_run_from_pipeline_func(median_stop, arguments={}, namespace='user namespace') TektonClient().cr...
samples/katib/early-stopping.ipynb
kubeflow/kfp-tekton
apache-2.0
Remember that IPython and Jupyter will automatically (and conveniently!) call the __repr__ of an object if it is the last thing in the cell. But I'll use the print() function explicitly just to be clear. This displays the string representation of the object. It usually includes: an object type (class) an object nam...
# now *call* the function by using parens output = duplicator('yo') # verify the expected behavior print(output)
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Because functions are objects, they have attributes just like any other Python object.
# the dir() built-in function displays the argument's attributes dir(duplicator)
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Because functions are objects, we can pass them around like any other data type. For example, we can assign them to other variables! If you occasionally still have dreams about the Enumerator, this will look familiar.
# first, recall the normal behavior of useful_function() duplicator('ring') # now create a new variable and assign our function to it another_duplicator = duplicator # now, we can use the *call* notation because the new variable is # assigned the original function another_duplicator('giggity') # and we can verify...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
By looking at the memory location, we can see that the second function is just a pointer to the first function! Cool! Functions inside functions With an understanding of what's inside a function and what we can do with it, consider the case were we define a new function within another function. This may seem overly co...
def speaker(): """ Simply return a word (a string). Other than possibly asking 'why are you writing this simple function in such a complicated fashion?' this should hopefuly should be pretty clear. """ # define a local variable word='hello' def shout(): """Re...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Now, this may be intuitive, but it's important to note that the inner function is not accessible outside of the outer function. The interpreter can always step out into larger (or "more outer") namespaces, but we can't dig deeper into smaller ones.
try: # this function only exists in the local scope of the outer function shout() except NameError, e: print(e)
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Functions out of functions What if we'd like our outer function to return a function? For example, return the inner function instead of the return value of the inner function.
def speaker_func(): """Similar to speaker(), but this time return the actual inner function!""" word = 'hello' def shout(): """Return an all-caps version of the passed word.""" return word.upper() # don't *call* shout(), just return it return shout # remember: our fun...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Remember that the return value of the outer function is another function. And just like we saw earlier, we can print the function to see the name and memory location. Note that the name is that of the inner function. Makes sense, since that's what we returned. Like we said before, since this is an object, we can pass t...
# this will assign to the variable new_shout, a value that is the shout function new_shout = speaker_func()
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Which means we can also call it with parens, as usual.
# which means we can *call* it new_shout()
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Functions into functions If functions are objects, we can just as easily pass a function into another function. You've probably seen this before in the context of sorting, or maybe using map:
from operator import itemgetter # we might want to sort this by the first or second item tuple_list = [(1,5),(9,2),(5,4)] # itemgetter is a callable (like a function) that we pass in as an argument to sorted() sorted(tuple_list, key=itemgetter(1)) def tuple_add(tup): """Sum the items in a tuple.""" return su...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
If we can pass functions into and out of other functions, then I propose that we can extend or modify the behavior of a function without actually editing the original function! Decorators 🎉💥🎉💥🎉💥🎉💥🎉💥 For example, say there's some previously-defined function in and you'd like it to be more verbose. For now, let...
def verbose(func): """Add some marginally annoying verbosity to the passed func.""" def inner(): print("heeeeey everyone, I'm about to do a thing!") print("hey hey hey, I'm about to call a function called: {}".format(func.__name__)) print # now call (and print) the passed fu...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Now, imagine we have a function that we wish had more of this type of "logging." But, we don't want to jump in and add a bunch of code to the original function.
# here's our original function (that we don't want to modify) def say_hi(): """Return 'hi'.""" return '--> hi. <--' # understand the original behavior of the function say_hi()
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Instead, we pass the original function as an arg to our verbose function. Remember that this returns the inner function, so we can assign it and then call it.
# this is now a function... verbose_say_hi = verbose(say_hi) # which we can call... verbose_say_hi()
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Looking at the output, we can see that when we called verbose_say_hi(), all of the code in it ran: two print statements then the passed function say_hi() was called it's return value was printed finally, there was some other printing defined in the inner function We'd now say that verbose_say_hi() is a decorated ve...
# this will clobber the existing namespace value (the original function def). # in it's place we have the verbose version! say_hi = verbose(say_hi) say_hi()
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Uneditable source code One use-case where this technique can be useful is when you need to use an existing base of code that you can't edit. There's an existing library that defines classes and methods that are aligned with your needs, but you need a slight variation on them. Imagine there is a library called (creative...
! cat _uneditable_lib.py
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
BUT Imagine you don't actually have the Python source, you have the compiled binary. Try opening this file in vi and see how it looks.
! ls | grep .pyc # you can still *use* the compiled code from uneditable_lib import Coordinate, add # make a couple of coordinates using the existing library coord_1 = Coordinate(x=100, y=200) coord_2 = Coordinate(x=-500, y=400) print( coord_1 ) print( add(coord_1, coord_2) )
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
But, imagine that for our particular use-case, we need to confine the resulting coordinates to the first quadrant (that is, x &gt; 0 and y &gt; 0). We want any negative component in the coordinates to just be truncated to zero. We can't edit the source code, but we can decorate (and modify) it!
def coordinate_decorator(func): """Decorates the pre-built source code for Coordinates. We need the resulting coordinates to only exist in the first quadrant, so we'll truncate negative values to zero. """ def checker(a, b...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
We can decorate the preexisting add() function with our new wrapper. And since we may be using other code from uneditable_lib with an API that expects the function to still be called add(), we can just overwrite that namespace variable.
# first we decorate the existing function add = coordinate_decorator(add) # then we can call it as before print( add(coord_1, coord_2) )
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
And, we now have a truncated Coordinate that lives in the first quadrant.
from IPython.display import Image Image(url='http://i.giphy.com/8VrtCswiLDNnO.gif')
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
If we are running out of time, this is an ok place to wrap up. Examples Here are some real examples you might run across in the wild: Flask (web framework) uses decorators really well @app.route is a decorator that lets you decorate an arbitrary Python function and turn it into a URL path. @login_required is a decorat...
def say_bye(): """Return 'bye'.""" return '--> bye. <--' say_bye()
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Remember the verbose() decorator that we already created? If this function (and perhaps others) should be made verbose at the time they're defined, we can apply the decorator right then and there using the @ shorthand:
@verbose def say_bye(): """Return 'bye'.""" return '--> bye. <--' say_bye() Image(url='http://i.giphy.com/piupi6AXoUgTe.gif')
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
But that shouldn't actually blow your mind. Based on our discussion before, you can probably guess that the decorator notation is just shorthand for: say_bye = verbose( say_bye ) One place where this shorthand can come in particularly handy is when you need to stack a bunch of decorators. In place of nested decorators...
# -c option starts a new interpreter session in a subshell and evaluates the code in quotes. # here, we just assign the value 3 to the variable x and print the global namespace ! python -c 'x=3; print( globals() )'
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Note that there are a bunch of other dunder names that are in the global namespace. In particular, note that '__name__' = '__main__' because we ran this code from the command line (a comparison that you've made many times in the past!). And you can see the variable x that we assigned the value of 3. We can also look a...
# this var is defined at the "outermost" level of this code block z = 10 def printer(x): """Print some things to stdout.""" # create a new var within the scope of this function animal = 'baboon' # ask about the namespace of the inner-most scope, "local" scope print('local namespace: {}\n'...
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
First, you can see that when our scope is 'inside the function', the namespace is very small. It's the local variables defined within the function, including the arg we passed the function. But, you can also see that we can still "see" the variable z, which was defined outside the function. This is because even though...
try: # remember that this var was created and assigned only within the function animal except NameError, e: print(e)
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
Closures This is all relevant, because part of the mechanism behind a decorator is the concept of a function closure. A function closure captures the enclosing state (namespace) at the time a non-global function is defined. To see an example, consider the following code:
def outer(x): def inner(): print x return inner
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
We saw earlier, that the variable x isn't directly accessible outside of the function outer() because it's created within the scope of that function. But, Python's function closures mean that because inner() is not defined in the global scope, it keeps track of the surrounding namespace wherein it was defined. We can ...
o = outer(7) o() try: x except NameError, e: print(e) print( dir(o) ) print( o.func_closure )
python-decorators-101/python-decorators-101.ipynb
fionapigott/Data-Science-45min-Intros
unlicense
1. Data input (source)
# do not forget to call "Update()" at the end of the reader rectGridReader = vtk.vtkRectilinearGridReader() rectGridReader.SetFileName("data/jet4_0.500.vtk") rectGridReader.Update()
.ipynb_checkpoints/05_NB_VTKPython_Scalar-checkpoint.ipynb
dianafprieto/SS_2017
mit
2. Filters Filter 1: vtkRectilinearGridOutlineFilter() creates wireframe outline for a rectilinear grid.
rectGridOutline = vtk.vtkRectilinearGridOutlineFilter() rectGridOutline.SetInputData(rectGridReader.GetOutput())
.ipynb_checkpoints/05_NB_VTKPython_Scalar-checkpoint.ipynb
dianafprieto/SS_2017
mit
3. Mappers Mapper: vtkPolyDataMapper() maps vtkPolyData to graphics primitives.
rectGridOutlineMapper = vtk.vtkPolyDataMapper() rectGridOutlineMapper.SetInputConnection(rectGridOutline.GetOutputPort())
.ipynb_checkpoints/05_NB_VTKPython_Scalar-checkpoint.ipynb
dianafprieto/SS_2017
mit
4. Actors
outlineActor = vtk.vtkActor() outlineActor.SetMapper(rectGridOutlineMapper) outlineActor.GetProperty().SetColor(0, 0, 0)
.ipynb_checkpoints/05_NB_VTKPython_Scalar-checkpoint.ipynb
dianafprieto/SS_2017
mit
5. Renderers and Windows
#Option 1: Default vtk render window renderer = vtk.vtkRenderer() renderer.SetBackground(0.5, 0.5, 0.5) renderer.AddActor(outlineActor) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(500, 500) renderWindow.Render() iren = vtk.vtkRenderWindowInteract...
.ipynb_checkpoints/05_NB_VTKPython_Scalar-checkpoint.ipynb
dianafprieto/SS_2017
mit
### More Information The build_picklist_from_txtl_setup_csvs function is used for creating a picklist from a TX-TL setup spreadsheet (version 2.0 or later -- spreadsheets from before late 2016 will not work). You will need to feed it the names of two CSV files produced from the "recipe" sheet (the first sheet, containi...
import murraylab_tools.echo as mt_echo import os.path # Relevant input and output files. Check these out for examples of input file format. dilution_inputs = os.path.join("2D_dilution_series", "inputs") dilution_outputs = os.path.join("2D_dilution_series", "outputs") plate_file = os.path.join(dilution_inputs, "dilut...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
Note the warnings -- a lot of mistakes you might make will cause you to pipette 0 nL at a time, so the code will warn you if you do so. In this case, those 0 volume pipetting steps are normal -- you just added a material to 0 concentration. Similar warnings will appear if you under-fill a reaction. You can also manuall...
# Build an EchoRun object dilution_plate = mt_echo.SourcePlate(filename = plate_file) default_master_mix = mt_echo.MasterMix(plate = dilution_plate) dilution_echo_calculator = mt_echo.EchoRun(plate = dilution_plate, master_mix = default_master_mix) # Plan out a dilution series starting_well = "D2" dilution_echo_calcul...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
...then we can add, say, bananas, to a 2x2 square in the top-left corner of the reaction.
# Bananas at 100 nM bananas = mt_echo.EchoSourceMaterial('Cavendish', 100, 0, None) dilution_echo_calculator.add_material_to_block(bananas, 3, 'D2', 'E3')
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
You can also add to a single well, if you really need to.
old_bananas = mt_echo.EchoSourceMaterial('Gros Michel', 100, 0, None) dilution_echo_calculator.add_material_to_well(old_bananas, 3, 'F5')
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
More Information The build_dilution_series function of EchoRun is useful for quickly building a grid of dilutions of two materials, one on each axis. This is useful for double titrations of, for example, plasmid vs. inducer, or titration of two inputs. If you want to do anything more complex, you'll probably need to mo...
import murraylab_tools.echo as mt_echo import os.path # Relevant input and output files. Check these out for examples of input file format. assoc_inputs = os.path.join("association_list", "inputs") assoc_outputs = os.path.join("association_list", "outputs") stock_file = os.path.join(assoc_inputs, 'association_source...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
More Information The build_picklist_from_association_spreadsheet function is used for arbitrary mappings of source plate wells to destination wells, using 1) a spreadsheet describing the contents of each source plate, and 2) a second spreadsheet describing what materials should be put in what wells, and at what concent...
import murraylab_tools.echo as mt_echo import os.path plate_file = os.path.join("tweaking", "plate_file_example.dat") # Build an EchoRun object example_plate = mt_echo.SourcePlate(filename = plate_file) example_master_mix = mt_echo.MasterMix(example_plate) example_echo_calculator = mt_echo.EchoRun(plate = example_pla...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To change the reaction volume: Reaction volume is a property of an EchoRun object.
example_echo_calculator.rxn_vol = 10.5 * 1e3 # Volume IN nL!!!
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
Make sure to run this before running build_picklist_from_association_spreadsheet or build_dilution_series. You almost certainly shouldn't do this at all when using build_picklist_from_txtl_setup_csvs, because that function will automatically extract a reaction volume from the setup spreadsheet. To change the master mix...
new_master_mix = mt_echo.MasterMix(example_plate, extract_fraction = 0.40, rxn_vol = example_echo_calculator.rxn_vol) example_echo_calculator.add_master_mix(new_master_mix) example_echo_calculator.build_dilution_series(gfp, atc, gfp_final_concentrations, ...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
You can also add arbitrary components to the master mix. For example, the following code ads the dye DFHBI-1T to every well at a final concentration of 10 µM, from a 2 mM stock:
new_master_mix = mt_echo.MasterMix(example_plate, rxn_vol = example_echo_calculator.rxn_vol) dfhbi = mt_echo.EchoSourceMaterial("DFHBI-1T", 2000, 0, example_plate) new_master_mix.add_material(dfhbi, 10) example_echo_calculator.add_master_mix(new_master_mix) example_echo_calculator.bu...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To change buffer/extract aliquot size: Buffer and extract aliquot size are controlled by the MasterMix object. Like extract percentage, aliquot sizes can be changed in the MasterMix's constructor. Note that both aliquot sizes are in units of nL, not uL.
new_master_mix = mt_echo.MasterMix(example_plate, extract_per_aliquot = 50000, buffer_per_aliquot = 70000, rxn_vol = example_echo_calculator.rxn_vol) example_echo_calculator.add_master_mix(new_master_mix) example_ec...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To run a (dilution series) reaction without master mix: You can also make a dilution series without any master mix by either creating a new EchoRun object with None for its MasterMix, or by removing the MasterMix on an existing EchoRun object with a call to remove_master_mix.
dye1 = mt_echo.EchoSourceMaterial('A Dye', 100, 0, dilution_plate) dye2 = mt_echo.EchoSourceMaterial('Another Dye', 122, 0, dilution_plate) dye_concentrations = [x for x in range(10)] example_echo_calculator.remove_master_mix() example_echo_calculator.build_dilution_series(dye1, dye2, dye_concentrations, ...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To change the source plate type/material type: Source plate types and material types are set as optional arguments in the constructor of a SourcePlate object. The type and material of a source plate are both set by a string, which can be any string that the Echo Plate Reformat software will recognize.
plate_type = "384PP_AQ_BP" # This is actually the default plate value retyped_example_plate = mt_echo.SourcePlate(filename = plate_file, SPtype = plate_type) another_example_echo_calculator = mt_echo.EchoRun(plate = retyped_example_plate)
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To change the source plate name: Source plate names are set much like source plate types with the argument SPname. In addition, as a shorthand, you can set SPname to be a number N, in which case the plate will be named Source[N].
plate_name = "FirstPlate" renamed_example_plate = mt_echo.SourcePlate(filename = plate_file, SPname = plate_name) yet_another_example_echo_calculator = mt_echo.EchoRun(plate = renamed_example_plate)
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To change the destination plate type: Destination plate types are determined and stored directly in the EchoRun object. The destination plate type can be set by the optional argument DPtype in the constructor of an EchoRun object, or set manually any time before calling write_picklist on that EchoRun.
calculator_with_odd_destination = mt_echo.EchoRun(plate = example_plate, DPtype = "some_96_well_plate") calculator_with_odd_destination.DPtype = "Nunc_384_black_glassbottom" # Just kidding! # ... # calculator_with_odd_destination.write_picklist(...) #...
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
To change dead volume and max volume: You probably shouldn't do this. If you absolutely must squeeze every last bit of efficiency out of your source wells, you can set the dead_volume and max_volume variables, which are static variables in the murraylab_tools.echo package. If you change them, also make sure to set the ...
from murraylab_tools.echo.echo_functions import dead_volume, max_volume, usable_volume dead_volume = 10000 # Volume in nL! max_volume = 75000 # Volume in nL! usable_volume = max_volume - dead_volume # Don't forget to re-calculate this!
examples/Echo Setup Usage Examples.ipynb
smsaladi/murraylab_tools
mit
Extracting the samples we are interested in
# Let's extract ADHd and Bipolar patients (mutually exclusive) ADHD_men = X.loc[X['ADHD'] == 1] ADHD_men = ADHD_men.loc[ADHD_men['Bipolar'] == 0] BP_men = X.loc[X['Bipolar'] == 1] BP_men = BP_men.loc[BP_men['ADHD'] == 0] ADHD_cauc = Y.loc[Y['ADHD'] == 1] ADHD_cauc = ADHD_cauc.loc[ADHD_cauc['Bipolar'] == 0] BP_cauc ...
Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb
Upward-Spiral-Science/spect-team
apache-2.0
Dimensionality reduction Manifold Techniques ISOMAP
combined1 = pd.concat([ADHD_men, BP_men]) combined2 = pd.concat([ADHD_cauc, BP_cauc]) print combined1.shape print combined2.shape combined1 = preprocessing.scale(combined1) combined2 = preprocessing.scale(combined2) combined1 = manifold.Isomap(20, 20).fit_transform(combined1) ADHD_men_iso = combined1[:1056] BP_men_i...
Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb
Upward-Spiral-Science/spect-team
apache-2.0
Clustering and other grouping experiments K-Means clustering - iso
data1 = pd.concat([pd.DataFrame(ADHD_men_iso), pd.DataFrame(BP_men_iso)]) data2 = pd.concat([pd.DataFrame(ADHD_cauc_iso), pd.DataFrame(BP_cauc_iso)]) print data1.shape print data2.shape kmeans = KMeans(n_clusters=2) kmeans.fit(data1.get_values()) labels1 = kmeans.labels_ centroids1 = kmeans.cluster_centers_ print('Es...
Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb
Upward-Spiral-Science/spect-team
apache-2.0
As is evident from the above 2 experiments, no clear clustering is apparent.But there is some significant overlap and there 2 clear groups Classification Experiments Let's experiment with a bunch of classifiers
ADHD_men_iso = pd.DataFrame(ADHD_men_iso) BP_men_iso = pd.DataFrame(BP_men_iso) ADHD_cauc_iso = pd.DataFrame(ADHD_cauc_iso) BP_cauc_iso = pd.DataFrame(BP_cauc_iso) BP_men_iso['ADHD-Bipolar'] = 0 ADHD_men_iso['ADHD-Bipolar'] = 1 BP_cauc_iso['ADHD-Bipolar'] = 0 ADHD_cauc_iso['ADHD-Bipolar'] = 1 data1 = pd.concat([ADH...
Code/Assignment-10/SubjectSelectionExperiments (rCBF data).ipynb
Upward-Spiral-Science/spect-team
apache-2.0
Al usar la función open de webbrowser se abrirá el navegador o una pestaña nueva si el navegador ya estaba abierto. Ya que no indicamos el navegador, esto se realiza con el navegador configurado por defecto en nuestro sistema. Se puede usar para abrir pestañas y ventanas nuevas, cerrarlo, y tambien usar un navegador es...
webbrowser.open('http://github.com/')
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Sin embargo, la labor de extracción web depende de obtener el código fuente o elementos disponibles en las páginas, lo cual es imposible con solo abrir el navegador. Para este fin es posible usar urllib o como lo haremos en esta sesión, con request.
import requests res = requests.get('http://www.gutenberg.org/files/18251/18251-0.txt') res.status_code == requests.codes.ok # Validar código 200 (ok) type(res) len(res.text) print(res.text[:250])
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Ante un fallo en el proceso de obtención del código con la función get, es posible generar una notificación del motivo de fallo.
res = requests.get('http://github.com/yomeinventoesto') res.raise_for_status()
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Cuando obtenemos un elemento de una dirección, este se encuentra como binario y no como texto plano. Esto nos facilita algunas cosas. Nos permite descargar contenido que no se solo texto plano (archivos de texto o código fuente) sino tambien directamente archivos binarios como imagenes, ejecutables, videos, archivos de...
res = requests.get('http://www.programmableweb.com/sites/default/files/github-jupyter.jpg') archivo_imagen = open('github-jupyter.jpg', 'wb') for bloques in res.iter_content(100000): archivo_imagen.write(bloques) archivo_imagen.close()
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
En el bloque anterior, el método iter_content genera bloques del archivo con el tamaño indicado en su argumento. Esto conviene para la escritura de archivos de gran tamaño.
import bs4
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Usarmos ahora bs4 (forma de importar Beautiful Soup), lo cual nos permitirá la búsqueda de texto y estructuras html especificas. Este es más conveniente que usar expresiones regulares directamente en el código fuente. Al crear el objeto, debemos indicar el texto sobre el cual actuará (puede ser obtenido directamente ...
res = requests.get('https://github.com/cosmoscalibur/herramientas_computacionales') gh = bs4.BeautifulSoup(res.text, "lxml") type(gh)
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Ahora, buscaremos todas las estructuras td que tengan el atributo class con valor content.
tabla_archivos = gh.find_all('td', {'class':'content'}) type(tabla_archivos)
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
El resultado es una lista con todos los resultados obtenidos. Tambien es posible una búsqueda uno a uno, usando find en lugar de find_all.
len(tabla_archivos) print(tabla_archivos)
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
En el filtrado anterior, ahora buscaremos todas las etiquetas a las cuales asociamos con la presencia del atributo href. De esta forma localizaremos la lista de archivos. Para obtener el texto al interior de una etiqueta, usamos la propiedad string y el valor de un atributo con el método get.
for content in tabla_archivos: lineas_a = content('a') if lineas_a: texto = "Se encontro el archivo '{}'".format(lineas_a[0].string.encode("utf-8")) texto += " con enlace '{}'.".format(lineas_a[0].get("href")) print(texto)
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Nos vimos en la necesidad de usar encode("utf-8") ya que la codificación de la página es utf-8 y no ascii (el usado por defecto en python). Podemos consultar los atributos de una etiqueta o si posee un atributo especifico, y no solo obtener el valor, de la siguiente forma.
lineas_a[0].has_attr("href") # Existencia de un atributo lineas_a[0].attrs # Atributos existentes from selenium import webdriver
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Invocar la instancia del controlador del navegador depende del navegador de interes. Hay que tener encuenta que no todos los navegadores son soportados. Podemos encontrar soporte para Chrome, Firefox, Opera, IE y PhantomJS. Este último permite realizar la labor sin la generación de una ventana para el navegador (en cas...
browser = webdriver.Chrome("/home/cosmoscalibur/Downloads/chromedriver") browser.get('http://github.com') username = browser.find_element_by_id("user[login]") username.send_keys("cosmoscalibur@gmail.com") dar_click = browser.find_element_by_link_text("privacy policy") dar_click.click()
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Resulta bastante útil el uso de selenium no tanto en los casos que requieran de interacción sino en los casos donde los contenidos (incluye elementos de interacción) son de generación dinámica o tras la interacción el nuevo enlace o contenido tiene retrasos apreciables, lo cual evitaría que Request obtenga el código ad...
codigo = browser.page_source print(codigo)
Presentaciones/Notas/09_Extraccion_web.ipynb
cosmoscalibur/herramientas_computacionales
mit
Unlike in the previous case, where we had word files that we could export as plaintext, in this case Manuela has prepared a sample chapter with four editions transcribed in parallel in an office spreadsheet. So we first of all make sure that we have good UTF-8 comma-separated-value files, e.g. by uploading a csv export...
sourcePath = 'DHd2019/cap6_align_-_2018-01.csv'
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Then, we can go ahead and open the file in python's csv reader:
import csv sourceFile = open(sourcePath, newline='', encoding='utf-8') sourceTable = csv.reader(sourceFile)
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
And next, we read each line into new elements of four respective lists (since we're dealing with one sample chapter, we try to handle it all in memory first and see if we run into problems): (Note here and in the following that in most cases, when the program is counting, it does so beginning with zero. Which means tha...
import re # Initialize a list of lists, or two-dimensional list ... Editions = [[]] # ...with four sub-lists 0 to 3 for i in range(3): a = [] Editions.append(a) # Now populate it from our sourceTable sourceFile.seek(0) # in repeated runs, restart from the beginning of the file for row in sourceTa...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Actually, let's define two more list variables to hold information about the different editions - language and year of print:
numOfEds = 4 language = ["PT", "PT", "ES", "LA"] # I am using language codes that later on can be used in babelnet year = [1549, 1552, 1556, 1573]
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
TF/IDF <a name="tfidf"></a> In the previous (i.e. Solórzano) analyses, things like tokenization, lemmatization and stop-word lists filtering are explained step by step. Here, we rely on what we have found there and feed it all into functions that are ready-made and available in suitable libraries... First, we build our...
lemma = [{} for i in range(numOfEds)] # lemma = {} # we build a so-called dictionary for the lookups for i in range(numOfEds): wordfile_path = 'Azpilcueta/wordforms-' + language[i].lower() + '.txt' # open the wordfile (defined above) for reading wordfile = open(wordfile_path, encoding='utf-8') ...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Again, a quick test: Let's see with which "lemma"/basic word the particular wordform "diremos" is associated, or, in other words, what value our lemma variable returns when we query for the key "diremos":
lemma[language.index("PT")]['diremos']
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
And we are going to need the stopwords lists:
stopwords = [] for i in range(numOfEds): stopwords_path = 'DHd2019/stopwords-' + language[i].lower() + '.txt' stopwords.append(open(stopwords_path, encoding='utf-8').read().splitlines()) print(str(len(stopwords[i])) + ' ' + language[i] + ' stopwords known to the system, e.g.: ' + str(stopwo...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
(In contrast to simpler numbers that have been filtered out by the stopwords filter, I have left numbers representing years like "1610" in place.) And, later on when we try sentence segmentation, we are going to need the list of abbreviations - words where a subsequent period not necessarily means a new sentence:
abbreviations = [] # As of now, this is one for all languages :-( abbrs_path = 'DHd2019/abbreviations.txt' abbreviations = open(abbrs_path, encoding='utf-8').read().splitlines() print(str(len(abbreviations)) + ' abbreviations known to the system, e.g.: ' + str(abbreviations[100:119]))
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Next, we should find some very characteristic words for each segment for each edition. (Let's say we are looking for the "Top 20".) We should build a vocabulary for each edition individually and only afterwards work towards a common vocabulary of several "Top n" sets.
import re import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer numTopTerms = 20 # So first we build a tokenising and lemmatising function (per language) to work as # an input filter to the CountVectorizer function def ourLaLemmatiser(str_input): wordforms = re.split('\W+', str_input) ...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Translations? Maybe there is an approach to inter-lingual comparison after all. After a first unsuccessful try with conceptnet.io, I next want to try Babelnet in order to lookup synonyms, related terms and translations. I still have to study the API... For example, let's take this single segment 19:
segment_no = 18
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
And then first let's see how this segment compares in the different editions:
print("Comparing words from segments " + str(segment_no) + " ...") print(" ") print("Here is the segment in the four editions:") print(" ") for i in range(numOfEds): print("Ed. " + str(i) + ":") print("------") print(Editions[i][segment_no]) print(" ") print(" ") print(" ") # Build List of most signif...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Now we look up the "concepts" associated to those words in babelnet. Then we look up the concepts associated with the words of the present segment from another edition/language, and see if the concepts are the same. But we have to decide on some particular editions to get things started. Let's take the Spanish and Lati...
startEd = 1 secondEd = 2
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
And then we can continue...
import urllib import json from collections import defaultdict babelAPIKey = '18546fd3-8999-43db-ac31-dc113506f825' babelGetSynsetIdsURL = "https://babelnet.io/v5/getSynsetIds?" + \ "targetLang=LA&targetLang=ES&targetLang=PT" + \ "&searchLang=" + language[startEd] + \ ...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Actually I think this is somewhat promising - an overlap of four independent, highly meaning-bearing words, or of forty-something related concepts. At first glance, they should be capable of distinguishing this section from all the other ones. However, getting this result was made possible by quite a bit of manual tuni...
from nltk import sent_tokenize ## First, train the sentence tokenizer: from pprint import pprint from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars, PunktTrainer class BulletPointLangVars(PunktLanguageVars): sent_end_chars = ('.', '?', ':', '!', '¶') trainer = PunktTrainer() trainer.INCLU...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
... lemmatize/stopwordize it---
# folder for the several segment files: outputBase = 'Azpilcueta/sentences-lemmatized' dest = None # Then, sentence-tokenize our segments: for i in range(numOfEds): dest = open(outputBase + '_' + str(year[i]) + '.txt', encoding='utf-8', mode='w') stp = set(stopword...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
With these preparations made, Hunaligning 1552 and 1556 reports "Quality 0.63417" for unlemmatized and "Quality 0.51392" for lemmatized versions of the texts for its findings which still contain many errors. Removing ":" from the sentence end marks gives "Quality 0.517048/0.388377", but from a first impression with few...
from sklearn.metrics.pairwise import cosine_similarity similarities = pd.DataFrame(cosine_similarity(tfidf_matrix)) similarities[round(similarities, 0) == 1] = 0 # Suppress a document's similarity to itself print("Pairwise similarities:") print(similarities) print("The two most similar segments in the corpus are") pr...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
<div class="alert alertbox alert-success">Of course, in every set of documents, we will always find two that are similar in the sense of them being more similar to each other than to the other ones. Whether or not this actually *means* anything in terms of content is still up to scholarly interpretation. But at least i...
from wordcloud import WordCloud import matplotlib.pyplot as plt # We make tuples of (lemma, tf/idf score) for one of our segments # But we have to convert our tf/idf weights to pseudo-frequencies (i.e. integer numbers) frq = [ int(round(x * 100000, 0)) for x in Editions[1][3]] freq = dict(zip(fn, frq)) wc = WordCloud...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
In order to have a nicer overview over the many segments than is possible in this notebook, let's create a new html file listing some of the characteristics that we have found so far...
outputDir = "Azpilcueta" htmlfile = open(outputDir + '/Overview.html', encoding='utf-8', mode='w') # Write the html header and the opening of a layout table htmlfile.write("""<!DOCTYPE html> <html> <head> <title>Section Characteristics</title> <meta charset="utf-8"/> </head> <body> ...
gallery/DHD2019_Azpilcueta.ipynb
awagner-mainz/notebooks
mit
Message Receive Time In JSBSim the IMU messages are requested to be sent at the real IMU rate of 819.2 Hz: &lt;output name="localhost" type="SOCKET" protocol="UDP" port="5123" rate="819.2"&gt; But there they are then processed in python for noise and binary packing. Then it's sent as UDP packets which may get lost. Le...
# Get the time difference between each ADIS message diff = [(rust_time[i+1] - t)*1000 for i, t in enumerate(rust_time[:-1])] fig, ax1 = plt.subplots(figsize=(18,7)) plt.title(r"rust-fc ADIS Message Interval") plt.ylabel(r"Time Since Last Sample [ms]") plt.xlabel(r"Sample Number [#]") plt.plot(range(len(diff)), diff, ...
analysis/results.ipynb
natronics/rust-fc
gpl-3.0
IMU Noisy Acceleration Here we see the noise put into the IMU data and the true acceleration.
fig, ax1 = plt.subplots(figsize=(18,7)) plt.title(r"rust-fc Recorded IMU Acceleration") plt.ylabel(r"Acceleration [m/s${}^2$]") plt.xlabel(r"Run Time [s]") plt.plot(rust_time, rust_accel_x, alpha=0.8, lw=0.5, label="rust-fc IMU 'Up'") plt.plot(rust_time, rust_accel_y, alpha=0.8, lw=0.5, label="rust-fc IMU 'Y'") plt.pl...
analysis/results.ipynb
natronics/rust-fc
gpl-3.0
State Tracking The flight comptuer only knows the Inertial state (acceleration). It keeps track of velocity and altitude by integrating this signal. Here we compare rust-fc internal state to the exact numbers from the simulator.
# Computer difference from FC State and simulation "real" numbers sim_idx = 0 vel = 0 alt = 0 i_count = 0 sim_matched_vel = [] vel_diff = [] alt_diff = [] for i, t in enumerate(rust_state_time): vel += rust_vel[i] alt += rust_alt[i] i_count += 1 if sim_time[sim_idx] < t: sim_matched_vel.append(...
analysis/results.ipynb
natronics/rust-fc
gpl-3.0
形状对象和画笔对象是最为抽象的形式。接下来,构造多个形状,如矩形和圆形:
class Rectangle(Shape): def __init__(self,long,width): self.name="Rectangle" self.param="Long:%s Width:%s"%(long,width) print ("Create a rectangle:%s"%self.param) class Circle(Shape): def __init__(self,radius): self.name="Circle" self.param="Radius:%s"%radius prin...
DesignPattern/BridgePattern.ipynb
gaufung/Data_Analytics_Learning_Note
mit
紧接着是构造多种画笔,如普通画笔和画刷:
class NormalPen(Pen): def __init__(self,shape): Pen.__init__(self,shape) self.type="Normal Line" def draw(self): print ("DRAWING %s:%s----PARAMS:%s"%(self.type,self.shape.getName(),self.shape.getParam())) class BrushPen(Pen): def __init__(self,shape): Pen.__init__(self,shape)...
DesignPattern/BridgePattern.ipynb
gaufung/Data_Analytics_Learning_Note
mit
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 fr...
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: Dictionar...
Udacity-Deep-Learning-Foundation-Nanodegree/Project-4/dlnd_language_translation.ipynb
joelowj/Udacity-Projects
apache-2.0