Search Results

Search found 236 results on 10 pages for 'p np'.

Page 5/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • vtk glyphs 3D, indenpently color and rotation

    - by user3684219
    I try to display thanks to vtk (python wrapper) several glyphs in a scene with each their own colour and rotation. Unfortunately, just the rotation (using vtkTensorGlyph) is taken in consideration by vtk. Reversely, just color is taken in consideration when I use a vtkGlyph3D. Here is a ready to use piece of code with a vtkTensorGlyph. Each cube should have a random color but there all will be in the same color. I read and read again the doc of vtk but I found no solution. Thanks in advance for any idea #!/usr/bin/env python # -*- coding: utf-8 -*- import vtk import scipy.linalg as sc import random as ra import numpy as np import itertools points = vtk.vtk.vtkPoints() # where to locate each glyph in the scene tensors = vtk.vtkDoubleArray() # rotation for each glyph tensors.SetNumberOfComponents(9) colors = vtk.vtkUnsignedCharArray() # should be the color for each glyph colors.SetNumberOfComponents(3) # let's make 10 cubes in the scene for i in range(0, 50, 5): points.InsertNextPoint(i, i, i) # position of a glyph colors.InsertNextTuple3(ra.randint(0, 255), ra.randint(0, 255), ra.randint(0, 255) ) # pick random color rot = list(itertools.chain(*np.reshape(sc.orth(np.random.rand(3, 3)).transpose(), (1, 9)).tolist())) # random rotation matrix (row major) tensors.InsertNextTuple9(*rot) polydata = vtk.vtkPolyData() # create the polydatas polydata.SetPoints(points) polydata.GetPointData().SetTensors(tensors) polydata.GetPointData().SetScalars(colors) cubeSource = vtk.vtkCubeSource() cubeSource.Update() glyphTensor = vtk.vtkTensorGlyph() glyphTensor.SetColorModeToScalars() # is it really work ? try: glyphTensor.SetInput(polydata) except AttributeError: glyphTensor.SetInputData(polydata) glyphTensor.SetSourceConnection(cubeSource.GetOutputPort()) glyphTensor.ColorGlyphsOn() # should not color all cubes independently ? glyphTensor.ThreeGlyphsOff() glyphTensor.ExtractEigenvaluesOff() glyphTensor.Update() # next is usual vtk code mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyphTensor.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren = vtk.vtkRenderer() ren.SetBackground(0.2, 0.5, 0.3) ren.AddActor(actor) renwin = vtk.vtkRenderWindow() renwin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) iren.SetRenderWindow(renwin) renwin.Render() iren.Initialize() renwin.Render() iren.Start()

    Read the article

  • Reading numpy arrays outside of Python

    - by Abiel
    In a recent question I asked about the fastest way to convert a large numpy array to a delimited string. My reason for asking was because I wanted to take that plain text string and transmit it (over HTTP for instance) to clients written in other programming languages. A delimited string of numbers is obviously something that any client program can work with easily. However, it was suggested that because string conversion is slow, it would be faster on the Python side to do base64 encoding on the array and send it as binary. This is indeed faster. My question now is, (1) how can I make sure my encoded numpy array will travel well to clients on different operating systems and different hardware, and (2) how do I decode the binary data on the client side. For (1), my inclination is to do something like the following import numpy as np import base64 x = np.arange(100, dtype=np.float64) base64.b64encode(x.tostring()) Is there anything else I need to do? For (2), I would be happy to have an example in any programming language, where the goal is to take the numpy array of floats and turn them into a similar native data structure. Assume we have already done base64 decoding and have a byte array, and that we also know the numpy dtype, dimensions, and any other metadata which will be needed. Thanks.

    Read the article

  • Multiple Unpacking Assignment in Python when you don't know the sequence length

    - by doug
    The textbook examples of multiple unpacking assignment are something like: import numpy as NP M = NP.arange(5) a, b, c, d, e = M # so of course, a = 0, b = 1, etc. M = NP.arange(20).reshape(5, 4) # numpy 5x4 array a, b, c, d, e = M # here, a = M[0,:], b = M[1,:], etc. (ie, a single row of M is assigned each to a through e) (My Q is not numpy specfic; indeed, i would prefer a pure python solution.) W/r/t the piece of code i'm looking at now, i see two complications on that straightforward scenario: i usually won't know the shape of M; and i want to unpack a certain number of items (definitely less than all items) and i want to put the remainder into a single container so back to the 5x4 array above, what i would very much like to be able to do is, for instance, assign the first three rows of M to a, b, and c respectively (exactly as above) and the rest of the rows (i have no idea how many there will be, just some positive integer) to a single container, all_the_rest = []. I'm not sure if i have explained this clearly; in any event, if i get feedback i'll promptly edit my Question.

    Read the article

  • Python optimization problem?

    - by user342079
    Alright, i had this homework recently (don't worry, i've already done it, but in c++) but I got curious how i could do it in python. The problem is about 2 light sources that emit light. I won't get into details tho. Here's the code (that I've managed to optimize a bit in the latter part): import math, array import numpy as np from PIL import Image size = (800,800) width, height = size s1x = width * 1./8 s1y = height * 1./8 s2x = width * 7./8 s2y = height * 7./8 r,g,b = (255,255,255) arr = np.zeros((width,height,3)) hy = math.hypot print 'computing distances (%s by %s)'%size, for i in xrange(width): if i%(width/10)==0: print i, if i%20==0: print '.', for j in xrange(height): d1 = hy(i-s1x,j-s1y) d2 = hy(i-s2x,j-s2y) arr[i][j] = abs(d1-d2) print '' arr2 = np.zeros((width,height,3),dtype="uint8") for ld in [200,116,100,84,68,52,36,20,8,4,2]: print 'now computing image for ld = '+str(ld) arr2 *= 0 arr2 += abs(arr%ld-ld/2)*(r,g,b)/(ld/2) print 'saving image...' ar2img = Image.fromarray(arr2) ar2img.save('ld'+str(ld).rjust(4,'0')+'.png') print 'saved as ld'+str(ld).rjust(4,'0')+'.png' I have managed to optimize most of it, but there's still a huge performance gap in the part with the 2 for-s, and I can't seem to think of a way to bypass that using common array operations... I'm open to suggestions :D

    Read the article

  • vectorize is indeterminate

    - by telliott99
    I'm trying to vectorize a simple function in numpy and getting inconsistent behavior. I expect my code to return 0 for values < 0.5 and the unchanged value otherwise. Strangely, different runs of the script from the command line yield varying results: sometimes it works correctly, and sometimes I get all 0's. It doesn't matter which of the three lines I use for the case when d <= T. It does seem to be correlated with whether the first value to be returned is 0. Any ideas? Thanks. import numpy as np def my_func(d, T=0.5): if d > T: return d #if d <= T: return 0 else: return 0 #return 0 N = 4 A = np.random.uniform(size=N**2) A.shape = (N,N) print A f = np.vectorize(my_func) print f(A) $ python x.py [[ 0.86913815 0.96833127 0.54539153 0.46184594] [ 0.46550903 0.24645558 0.26988519 0.0959257 ] [ 0.73356391 0.69363161 0.57222389 0.98214089] [ 0.15789303 0.06803493 0.01601389 0.04735725]] [[ 0.86913815 0.96833127 0.54539153 0. ] [ 0. 0. 0. 0. ] [ 0.73356391 0.69363161 0.57222389 0.98214089] [ 0. 0. 0. 0. ]] $ python x.py [[ 0.37127366 0.77935622 0.74392301 0.92626644] [ 0.61639086 0.32584431 0.12345342 0.17392298] [ 0.03679475 0.00536863 0.60936931 0.12761859] [ 0.49091897 0.21261635 0.37063752 0.23578082]] [[0 0 0 0] [0 0 0 0] [0 0 0 0] [0 0 0 0]]

    Read the article

  • how do I remove rows/columns from this matrix using python

    - by banditKing
    My matrix looks like this. ['Hotel', ' "excellent"', ' "very good"', ' "average"', ' "poor"', ' "terrible"', ' "cheapest"', ' "rank"', ' "total reviews"'] ['westin', ' 390', ' 291', ' 70', ' 43', ' 19', ' 215', ' 27', ' 813'] ['ramada', ' 136', ' 67', ' 53', ' 30', ' 24', ' 149', ' 49', ' 310 '] ['sutton place', '489', ' 293', ' 106', ' 39', ' 20', ' 299', ' 24', ' 947'] ['loden', ' 681', ' 134', ' 17', ' 5', ' 0', ' 199', ' 4', ' 837'] ['hampton inn downtown', ' 241', ' 166', ' 26', ' 5', ' 1', ' 159', ' 21', ' 439'] ['shangri la', ' 332', ' 45', ' 20', ' 8', ' 2', ' 325', ' 8', ' 407'] ['residence inn marriott', ' 22', ' 15', ' 5', ' 0', ' 0', ' 179', ' 35', ' 42'] ['pan pacific', ' 475', ' 262', ' 86', ' 29', ' 16', ' 249', ' 15', ' 868'] ['sheraton wall center', ' 277', ' 346', ' 150', ' 80', ' 26', ' 249', ' 45', ' 879'] ['westin bayshore', ' 390', ' 291', ' 70', ' 43', ' 19', ' 199', ' 813'] I want to remove the top row and the 0th column from this and create a new matrix. How do I do this? Normally in java or so Id use the following code: for (int y; y< matrix[x].length; y++) for(int x; x < matrix[Y].length; x++) { if(x == 0 || y == 0) { continue } else { new_matrix[x][y] = matrix[x][y]; } } Is there a way such as this in python to iterate and selectively copy elements? Thanks EDIT Im also trying to convert each matrix element from a string to a float as I iterate over the matrix. This my updated modified code based on the answer below. A = [] f = open("csv_test.csv",'rt') try: reader = csv.reader(f) for row in reader: A.append(row) finally: f.close() new_list = [row[1:] for row in A[1:]] l = np.array(new_list) l.astype(np.float32) print l However Im getting an error --> l.astype(np.float32) print l ValueError: setting an array element with a sequence.

    Read the article

  • install bluetooth in samsung R430, windows 7

    - by voodoomsr
    how can i install the bluetooth driver in this laptop in windows 7. The installation process tells me that i need to activate the bluetooth device to continue, but how can i activate if till that moment the device doesn't exist. There isn't any button or switch to activate the device manually. Edited: it's the np-r430 model. I read somewhere (a users forum, not official info) that for Chile and Argentina this models doesn't have built in the bluetooth device, but the US models have it. Maybe for some political and weird reason they send to south american laptops without that. The link of my notebook's specifications in an AR domain: np-r40

    Read the article

  • Post build events using ROBOCOPY instead of XCOPY

    - by Vizioz Limited
    I don't know about you, but for a long time I have used XCOPY statements in my Visual Studio post build events to copy my Umbraco files from the project folders to the local version of the website associated with the project.For the last few months we have been building a website framework for a client, who has subsequently sold the site to 5 clients, each with a different skin and some variations in their functional requirements.So, we now have a single source solutions, that builds and copies the site files into 5 seperate local websites, which enables us to easily test them all, what we had found was that this process was starting to slow up our build process and was reaching 30-45 seconds on a high spec Quad core machine (and slower on others)Today I asked Colin to create seperate Solution Configurations within Visual Studio so that while we were developing we could target a single site, and when we wanted to test all sites, we could target "ALL" and the Post Build script would then copy the files to all sites.This worked well, and with a couple of other optimisations, our build was now taking about 10 seconds for a single site.Then Colin came across ROBOCOPY and suggested that maybe this would be a suitable alternative to XCOPY, well, I had not heard of it.. (shock horror some of you shout, some I am sure like me, are also wondering what it is!)ROBOCOPY is new in Windows Vista & Windows 7 (you can also download it for XP & Windows 2003) and it has a lot of additional features, the two that were most interesting to us were:/MIR = Mirror a folder tree/XD = Exclude Directories/NP = No Progress (i.e. it does not give you a chart of it's results, which just fills up your Output window!)So, we set about implementing ROBOCOPY, we decided to use the /MIR switch on all folders that we knew were always stored in our project folders:- images- css- masterpages- xsltAnd for other files we just used the straight robocopy functionality.We also decided to exclude all the .SVN directories using the /XD switch and finally we added the /NP switch as mentioned above.The beauty of all of this, is the /MIR functionality, as this means that only files that have changed will be copied across which greatly speeds up the process, especially on the images folders which previously copied across on every build, now, if we add a new image to the project it will be copied across automatically and then never again, unless we change it of course!The build time now for all sites is approximately 4 seconds and for a single site, 2 seconds, I would highly recommend the time to make the same optimisations to your build processes if you have not done so already.

    Read the article

  • change password code error

    - by ejah85
    I've created a code to change a password. Now it seem contain an error. When I fill in the form to change password, and click save the error message: Warning: mysql_real_escape_string() expects parameter 2 to be resource, null given in C:\Program Files\xampp\htdocs\e-Complaint(FYP)\userChangePass.php on line 103 Warning: mysql_real_escape_string() expects parameter 2 to be resource, null given in C:\Program Files\xampp\htdocs\e-Complaint(FYP)\userChangePass.php on line 103 I really don’t know what the error message means. Please guys. Help me fix it. Here's is the code: <?php session_start(); ?> <?php # change password.php //set the page title and include the html header. $page_title = 'Change Your Password'; //include('templates/header.inc'); if(isset($_POST['submit'])){//handle the form require_once('connectioncomplaint.php');//connect to the db. //include "connectioncomplaint.php"; //create a function for escaping the data. function escape_data($data){ global $dbc;//need the connection. if(ini_get('magic_quotes_gpc')){ $data=stripslashes($data); } return mysql_real_escape_string($data, $dbc); }//end function $message=NULL;//create the empty new variable. //check for a username if(empty($_POST['userid'])){ $u=FALSE; $message .='<p> You forgot enter your userid!</p>'; }else{ $u=escape_data($_POST['userid']); } //check for existing password if(empty($_POST['password'])){ $p=FALSE; $message .='<p>You forgot to enter your existing password!</p>'; }else{ $p=escape_data($_POST['password']); } //check for a password and match againts the comfirmed password. if(empty($_POST['password1'])) { $np=FALSE; $message .='<p> you forgot to enter your new password!</p>'; }else{ if($_POST['password1'] == $_POST['password2']){ $np=escape_data($_POST['password1']); }else{ $np=FALSE; $message .='<p> your new password did not match the confirmed new password!</p>'; } } if($u && $p && $np){//if everything's ok. $query="SELECT userid FROM access WHERE (userid='$u' AND password=PASSWORD('$p'))"; $result=@mysql_query($query); $num=mysql_num_rows($result); if($num == 1){ $row=mysql_fetch_array($result, MYSQL_NUM); //make the query $query="UPDATE access SET password=PASSWORD('$np') WHERE userid=$row[0]"; $result=@mysql_query($query);//run the query. if(mysql_affected_rows() == 1) {//if it run ok. //send an email,if desired. echo '<p><b>your password has been changed.</b></p>'; include('templates/footer.inc');//include the HTML footer. exit();//quit the script. }else{//if it did not run OK. $message= '<p>Your password could not be change due to a system error.We apolpgize for any inconvenience.</p><p>' .mysql_error() .'</p>'; } }else{ $message= '<p> Your username and password do not match our records.</p>'; } mysql_close();//close the database connection. }else{ $message .='<p>Please try again.</p>'; } }//end oh=f the submit conditional. //print the error message if there is one. if(isset($message)){ echo'<font color="red">' , $message, '</font>'; } ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <body> <script language="JavaScript1.2">mmLoadMenus();</script> <table width="604" height="599" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td height="130" colspan="7"><img src="images/banner(E-Complaint)-.jpg" width="759" height="130" /></td> </tr> <tr> <td width="100" height="30" bgcolor="#ABD519"></td> <td width="100" bgcolor="#ABD519"></td> <td width="100" bgcolor="#ABD519"></td> <td width="100" bgcolor="#ABD519"></td> <td width="100" bgcolor="#ABD519"></td> <td width="160" bgcolor="#ABD519"> <?php include "header.php"; ?>&nbsp;</td> </tr> <tr> <td colspan="7" bgcolor="#FFFFFF"> <fieldset><legend> Enter your information in the form below:</legend> <p><b>User ID:</b> <input type="text" name="username" size="10" maxlength="20" value="<?php if(isset($_POST['userid'])) echo $_POST['userid']; ?>" /></p> <p><b>Current Password:</b> <input type="password" name="password" size="20" maxlength="20" /></p> <p><b>New Password:</b> <input type="password" name="password1" size="20" maxlength="20" /></p> <p><b>Confirm New Password:</b> <input type="password" name="password2" size="20" maxlength="20" /></p> </fieldset> <div align="center"> <input type="submit" name="submit" value="Change My Password" /></div> </form><!--End Form--> </td> </tr> </table> </body> </html>

    Read the article

  • Scipy interpolation on a numpy array

    - by dassouki
    I have a lookup table that is defined the following way: TR_ua1 = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8], [3.9, 7.3, 10.0, 13.1, 15.9], [4.5, 9.2, 12.2, 14.8, 18.2] ]) The header row elements are (hh) <1,2,3,4,5+ The header column (inc) elements are <10000, 20000, 20001+ The user will input a value ex (1.3, 25,000) or (0.2, 50,000). Scipy.interpolate() should interpolate to determine the correct value. Currently, the only way i can do this is with a bunch of if/elifs as exemplified below. I'm pretty sure there is a better, more efficient way of doing this Here's what i've got so far import numpy as np from scipy import interplate if (ua == 1): if (inc <= low_inc): #low_inc = 10,000 if (hh <= 1): return TR_ua1[0][0] elif (hh >= 1 & hh < 2): return interpolate( (1,2), (TR_ua1[0][1], TR_ua1[0][2]) )

    Read the article

  • AttributeError while adding colorbar in matplotlib

    - by bgbg
    The following code fails to run on Python 2.5.4: from matplotlib import pylab as pl import numpy as np data = np.random.rand(6,6) fig = pl.figure(1) fig.clf() ax = fig.add_subplot(1,1,1) ax.imshow(data, interpolation='nearest', vmin=0.5, vmax=0.99) pl.colorbar() pl.show() The error message is C:\temp>python z.py Traceback (most recent call last): File "z.py", line 10, in <module> pl.colorbar() File "C:\Python25\lib\site-packages\matplotlib\pyplot.py", line 1369, in colorbar ret = gcf().colorbar(mappable, cax = cax, ax=ax, **kw) File "C:\Python25\lib\site-packages\matplotlib\figure.py", line 1046, in colorbar cb = cbar.Colorbar(cax, mappable, **kw) File "C:\Python25\lib\site-packages\matplotlib\colorbar.py", line 622, in __init__ mappable.autoscale_None() # Ensure mappable.norm.vmin, vmax AttributeError: 'NoneType' object has no attribute 'autoscale_None' How can I add colorbar to this code? Following is the interpreter information: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>

    Read the article

  • Matplotlib subplots_adjust hspace so titles and xlabels don't overlap ?

    - by Denis
    With say 3 rows of subplots in matplotlib, xlabels of one row can overlap the title of the next; one has to fiddle with pl.subplots_adjust( hspace ), annoying. Is there a recipe for hspace that prevents overlaps and works for any nrow ? """ matplotlib xlabels overlap titles ? """ import sys import numpy as np import pylab as pl nrow = 3 hspace = .4 # of plot height, titles and xlabels both fall within this ?? exec "\n".join( sys.argv[1:] ) # nrow= ... y = np.arange(10) pl.subplots_adjust( hspace=hspace ) for jrow in range( 1, nrow+1 ): pl.subplot( nrow, 1, jrow ) pl.plot( y**jrow ) pl.title( 5 * ("title %d " % jrow) ) pl.xlabel( 5 * ("xlabel %d " % jrow) ) pl.show() My versions: matplotlib 0.99.1.1, python 2.6.4, Mac osx 10.4.11, backend: Qt4Agg (TkAgg = Exception in Tkinter callback) (For many extra points, can anyone outline how matplotlib's packer / spacer works, along the lines of chapter 17 "the packer" in the Tcl/Tk book ?)

    Read the article

  • store/load numpy array from binary files

    - by Javier
    Dear all, I would like to store and load numpy arrays from binary files. For that purposes, I created two small functions. Each binary file should contain the dimensionality of the given matrix. def saveArrayToFile(data, fileName): with open(fileName, 'w') as file: a = array.array('f') nSamples, ndim = data.shape a.extend([nSamples, ndim]) # write number of elements and dimensions a.fromstring(data.tostring()) a.tofile(file) def readArrayFromFile(fileName): _featDesc = np.fromfile(fileName, 'f') _ndesc = int(_featDesc[0]) _ndim = int(_featDesc[1]) _featDesc = _featDesc[2:] _featDesc = _featDesc.reshape([_ndesc, _ndim]) return _featDesc, _ndesc, _ndim An example on how to use the functions is: myarr=np.array([[7, 4],[3, 9],[1, 3]]) saveArrayToFile(myarr,'myfile.txt') _featDesc, _ndesc, _ndim = readArrayFromFile('myfile.txt') However, an error message of 'ValueError: total size of new array must be unchanged' is shown. My arrays can be of size MxN and MxM. Any suggestions are more than welcomed. I think the problem might be in the saveArrayToFile function. Best wishes, Javier

    Read the article

  • Compute divergence of vector field using python

    - by nyvltak
    Is there a function that could be used for calculation of the divergence of the vectorial field? (in matlab http://www.mathworks.ch/help/techdoc/ref/divergence.html) I would expect it exists in numpy/scipy but I can not find it using google :(. # I need to calculate div[A * grad(F)], where F = np.array([[1,2,3,4],[5,6,7,8]]) (2D numpy ndarray) A = np.array([[1,2,3,4],[1,2,3,4]]) (2D numpy ndarray) so grad(F) is a set of 2D ndarrays # I know, I can calculate divergence like this: http://en.wikipedia.org/wiki/Divergence#Application_in_Cartesian_coordinates but do not want to reinvent the wheel. (and also I expent there is some optimized function)

    Read the article

  • creating a color coded time chart using colorbar and colormaps in python

    - by Rusty
    I'm trying to make a time tracking chart based on a daily time tracking file that I used. I wrote code that crawls through my files and generates a few lists. endTimes is a list of times that a particular activity ends in minutes going from 0 at midnight the first day of the month to however many minutes are in a month. labels is a list of labels for the times listed in endTimes. It is one shorter than endtimes since the trackers don't have any data about before 0 minute. Most labels are repeats. categories contains every unique value of labels in order of how well I regard that time. I want to create a colorbar or a stack of colorbars (1 for eachday) that will depict how I spend my time for a month and put a color associated with each label. Each value in categories will have a color associated. More blue for more good. More red for more bad. It is already in order for the jet colormap to be right, but I need to get desecrate color values evenly spaced out for each value in categories. Then I figure the next step would be to convert that to a listed colormap to use for the colorbar based on how the labels associated with the categories. I think this is the right way to do it, but I am not sure. I am not sure how to associate the labels with color values. Here is the last part of my code so far. I found one function to make a discrete colormaps. It does, but it isn't what I am looking for and I am not sure what is happening. Thanks for the help! # now I need to develop the graph import numpy as np from matplotlib import pyplot,mpl import matplotlib from scipy import interpolate from scipy import * def contains(thelist,name): # checks if the current list of categories contains the one just read for val in thelist: if val == name: return True return False def getCategories(lastFile): ''' must determine the colors to use I would like to make a gradient so that the better the task, the closer to blue bad labels will recieve colors closer to blue read the last file given for the information on how I feel the order should be then just keep them in the order of how good they are in the tracker use a color range and develop discrete values for each category by evenly spacing them out any time not found should assume to be sleep sleep should be white ''' tracker = open(lastFile+'.txt') # open the last file # find all the categories categories = [] for line in tracker: pos = line.find(':') # does it have a : or a ? if pos==-1: pos=line.find('?') if pos != -1: # ignore if no : or ? name = line[0:pos].strip() # split at the : or ? if contains(categories,name)==False: # if the category is new categories.append(name) # make a new one return categories # find good values in order of last day newlabels=[] for val in getCategories(lastDay): if contains(labels,val): newlabels.append(val) categories=newlabels # convert discrete colormap to listed colormap python for ii,val in enumerate(labels): if contains(categories,val)==False: labels[ii]='sleep' # create a figure fig = pyplot.figure() axes = [] for x in range(endTimes[-1]%(24*60)): ax = fig.add_axes([0.05, 0.65, 0.9, 0.15]) axes.append(ax) # figure out the colors to use # stole this function to make a discrete colormap # http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations def cmap_discretize(cmap, N): """Return a discrete colormap from the continuous colormap cmap. cmap: colormap instance, eg. cm.jet. N: Number of colors. Example x = resize(arange(100), (5,100)) djet = cmap_discretize(cm.jet, 5) imshow(x, cmap=djet) """ cdict = cmap._segmentdata.copy() # N colors colors_i = np.linspace(0,1.,N) # N+1 indices indices = np.linspace(0,1.,N+1) for key in ('red','green','blue'): # Find the N colors D = np.array(cdict[key]) I = interpolate.interp1d(D[:,0], D[:,1]) colors = I(colors_i) # Place these colors at the correct indices. A = zeros((N+1,3), float) A[:,0] = indices A[1:,1] = colors A[:-1,2] = colors # Create a tuple for the dictionary. L = [] for l in A: L.append(tuple(l)) cdict[key] = tuple(L) # Return colormap object. return matplotlib.colors.LinearSegmentedColormap('colormap',cdict,1024) # jet colormap goes from blue to red (good to bad) cmap = cmap_discretize(mpl.cm.jet, len(categories)) cmap.set_over('0.25') cmap.set_under('0.75') #norm = mpl.colors.Normalize(endTimes,cmap.N) print endTimes print labels # make a color list by matching labels to a picture #norm = mpl.colors.ListedColormap(colorList) cb1 = mpl.colorbar.ColorbarBase(axes[0],cmap=cmap ,orientation='horizontal' ,boundaries=endTimes ,ticks=endTimes ,spacing='proportional') pyplot.show()

    Read the article

  • converting a treebank of vertical trees to s-expressions

    - by Andreas
    I need to preprocess a treebank corpus of sentences with parse trees. The input format is a vertical representation of trees, like so: S =NP ==(DT +def) the == (N +ani) man =VP ==V walks ...and I need it like: (S (NP (DT the) (N man)) (VP (V walks))) I have code that almost does it, but not quite. There's always a missing paren somewhere. Should I use a proper parser, maybe a CFG? The current code is at http://github.com/andreasvc/eodop/blob/master/arbobanko.py The code also contains real examples from the treebank.

    Read the article

  • How to suppress error messages in rpy2

    - by Björn
    Hello! The following code does not work. It seems that the R warning message raises a python error. # enable use of python objects in rpy2 import rpy2.robjects.numpy2ri import numpy as np from rpy2.robjects import r # create an example array a = np.array([[5,2,5],[3,7,8]]) # this line leads to a warning message, which in turn raises an # error message if run within a script. result = r['chisq.test'](a) Running that code example in ipython works, however, running it inside a script raises the errorTypeError: 'module' object is unsubscriptable. I assume this is due to the warning message. What is the best way to avoid this problem? Thanks in advance!

    Read the article

  • Values of Variables Matrix NumPy

    - by Max Mines
    I'm working on a program that determines if lines intersect. I'm using matrices to do this. I understand all the math concepts, but I'm new to Python and NumPy. I want to add my slope variables and yint variables to a new matrix. They are all floats. I can't seem to figure out the correct format for entering them. Here's an example: import numpy as np x = 2 y = 5 w = 9 z = 12 I understand that if I were to just be entering the raw numbers, it would look something like this: matr = np.matrix('2 5; 9 12') My goal, though, is to enter the variable names instead of the ints.

    Read the article

  • Distance between numpy arrays, columnwise

    - by Jaapsneep
    I have 2 arrays in 2D, where the column vectors are feature vectors. One array is of size F x A, the other of F x B, where A << B. As an example, for A = 2 and F = 3 (B can be anything): arr1 = np.array( [[1, 4], [2, 5], [3, 6]] ) arr2 = np.array( [[1, 4, 7, 10, ..], [2, 5, 8, 11, ..], [3, 6, 9, 12, ..]] ) I want to calculate the distance between arr1 and a fragment of arr2 that is of equal size (in this case, 3x2), for each possible fragment of arr2. The column vectors are independent of each other, so I believe I should calculate the distance between each column vector in arr1 and a collection of column vectors ranging from i to i + A from arr2 and take the sum of these distances (not sure though). Does numpy offer an efficient way of doing this, or will I have to take slices from the second array and, using another loop, calculate the distance between each column vector in arr1 and the corresponding column vector in the slice?

    Read the article

  • How to print the Control identifiers of a window to a document in Pywinauto.

    - by Swetha
    Hi All, I am trying to automate installation of an application using Pywinauto.During the installation the last window shows some warning or error messages in few cases and later the system begins to restart.My objective is to capture the the Warning messages which is possible by app.top_window_()._ctrl_identifiers() np.Notepad.Edit.TypeKeys(a,with_spaces=True, with_tabs=True, with_newlines=True) This is returning a list which contains all the messages of the screen. Second line is where i am trying to print the list object in the notepad.But its throwing some exceptions Traceback (most recent call last): File "", line 1, in np.Notepad.Edit.TypeKeys(a,with_spaces=True, with_tabs=True, with_newlines=True) File "C:\Python26\pywinauto\controls\HwndWrapper.py", line 950, in TypeKeys turn_off_numlock) File "C:\Python26\pywinauto\SendKeysCtypes.py", line 629, in SendKeys keys = parse_keys(keys, with_spaces, with_tabs, with_newlines) File "C:\Python26\pywinauto\SendKeysCtypes.py", line 538, in parse_keys c = string[index] KeyError: 0 Could anyone let me know how to do this or if there is other way in which this can be handled with an example. Thanks a lot in advance. Swetha

    Read the article

  • Python/Numpy - Save Array with Column AND Row Titles

    - by Scott B
    I want to save a 2D array to a CSV file with row and column "header" information (like a table). I know that I could use the header argument to numpy.savetxt to save the column names, but is there any easy way to also include some other array (or list) as the first column of data (like row titles)? Below is an example of how I currently do it. Is there a better way to include those row titles, perhaps some trick with savetxt I'm unaware of? import csv import numpy as np data = np.arange(12).reshape(3,4) # Add a '' for the first column because the row titles go there... cols = ['', 'col1', 'col2', 'col3', 'col4'] rows = ['row1', 'row2', 'row3'] with open('test.csv', 'wb') as f: writer = csv.writer(f) writer.writerow(cols) for row_title, data_row in zip(rows, data): writer.writerow([row_title] + data_row.tolist())

    Read the article

  • Animation with CGPoint in for loop

    - by user1066524
    I'm trying to do an animation where when a person clicks from point A to Point B on screen the object should slowly slide straight across (horizontally) from point A to Point B. I tried doing a for loop with something like: for (CGFloat i=previousPoint.x; i <= newPoint.x; i++){ [UIView animateWithDuration:10 delay:0 options:nil animations:^ { [magnifier removeFromSuperview]; magnifier = [[MagnifierView alloc] init]; CGPoint np = {i, newPoint.y}; magnifier.viewToMagnify = imageView; magnifier.touchPoint = np; [imageView addSubview:magnifier]; [magnifier setNeedsDisplay]; } completion:^(BOOL finished) { }]; } but for some reason it is moving it way up and then eventually to point B. sort of in a weird curve. how can I do this correctly?

    Read the article

  • If item not in the lst in scheme

    - by ms. sakura
    I'm working on context-free grammars, and I have a function that returns the (terminal values of grammar) for example: i have non-terminal function that results in (A B) , from calling say ((A cat) (B happy np) (A B sad)) so technically A and B are non terminals of the grammar. Now I want to be able to get the terminals (cat happy np sad) (define terminals (lambda (lsts) (cond ((null? lsts) lsts) ((not(member? (car(car lsts)) (n-terminals lsts))) (cons (car(car lsts)) (terminals (car (cdr lsts))))) (else (terminals (cdr lsts)))))) PS: functionality of n-terminals is described above. member? is a boolean function that returns true if an item is a member of the list, false otherwise. My function returns an empty lst. What am I missing here?

    Read the article

  • C# creating a queue to handle jobs triggered by FileSystemWatcher

    - by John S
    I have built a small tray app that will watch a folder and when a new file is added it runs a job. The job is to watch for video files and convert them to .mp4 using handBrakeCli. I have all this logic worked out. The problem I run into is that if there is more than one file I want it to queue the job til the prior one is complete. I am fairly new to c# and I am not sure of the best way to handle this. one idea is to create a queue somehow, a file to store the commands in order maybe, then execute the next one after the process is complete. We are dealing with large movie files here so it can take a while. I am doing this on a quad core with 8gb of RAM and it seems to generally take about 30mins to complete a full length movie. here is the code I have so far. there are some bits in here that are for future functionality so it refers to some classes that you wont see but it doesnt matter as they arent used here. any suggestions are welcome. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Diagnostics; using System.Threading; namespace movie_converter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } string hbCli; string cmd; string file; string strfilter = "*.*"; string[] filter = new string[3] { ".mkv", ".avi", ".wmv" }; //static list of types List<string> Ext = new List<string>(); //list of extensions to watch (dynamic) NotifyIcon notifyIcon = new System.Windows.Forms.NotifyIcon(); private void SetUpTrayIcon() { notifyIcon.BalloonTipText = "Movie Converter is running minimized."; notifyIcon.BalloonTipTitle = "I'm still here"; notifyIcon.Text = "John's movie converter"; notifyIcon.Icon = new Icon(@"C:\\Users\\John\\Pictures\\appicon.ico"); notifyIcon.Click += new EventHandler(notifyIcon_Click); if (notifyIcon != null) { notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(2000); } } private void Form_Resize(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) { this.Hide(); SetUpTrayIcon(); } } private void notifyIcon_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; notifyIcon.Visible = false; } public void Watcher() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = textBox1.Text + "\\"; //path to watch watcher.Filter = strfilter; //what types to look for set to * and i will filter later as it cant accept an array watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName; //properties to look at watcher.IncludeSubdirectories = true; //scan subdirs watcher.Created += new FileSystemEventHandler(OnChanged); //TODO: make this only run if the files are of a certain type watcher.EnableRaisingEvents = true; // start the watcher } static bool IsFileLocked(FileInfo file) { FileStream stream = null; try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); } catch (IOException) { //the file is unavailable because it is: //still being written to //or being processed by another thread //or does not exist (has already been processed) return true; } finally { if (stream != null) stream.Close(); } //file is not locked return false; } // Define the event handlers. private void OnChanged(object source, FileSystemEventArgs e) { string sFile = e.FullPath; //check that file is available FileInfo fileInfo = new FileInfo(sFile); while (IsFileLocked(fileInfo)) { Thread.Sleep(500); } if (System.Diagnostics.Process.GetProcessesByName("HandBrakeCLI").Length != 0) { Thread.Sleep(500); } else { //hbOptions hbCl = new hbOptions(); //hbCli = hbCl.HbCliOptions(); if (textBox3.Text != "") { hbCli = textBox3.Text.ToString(); } else { hbCli = "-e x264 -q 20 -B 160"; } string t = e.Name; string s = t.Substring(0, t.Length - 4); //TODO: fix this its not reliable file = e.FullPath; string opath = textBox1.Text.ToString(); cmd = "-i \"" + file + "\" -o \"" + opath + "\\" + s + ".mp4\" " + hbCli; try { for (int i = 0; i < Ext.Count(); i++) { if (e.Name.Contains(Ext[i])) { Process hb = new Process(); hb.StartInfo.FileName = "D:\\Apps\\Handbrake\\Install\\Handbrake\\HandBrakeCLI.exe"; hb.StartInfo.Arguments = cmd; notifyIcon.BalloonTipTitle = "Now Converting"; notifyIcon.BalloonTipText = file; notifyIcon.ShowBalloonTip(2000); hb.Start(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void button1_Click(object sender, EventArgs e) //ok button { //add each array item to the list for (int i = 0; i < filter.Count(); i++) { Ext.Add(filter[i]); } if (textBox1.Text != "" && textBox1.Text.Length > 2) { Watcher(); //call watcher to run } this.WindowState = FormWindowState.Minimized; } private void button2_Click(object sender, EventArgs e) //browse button { //broswe button DialogResult result = folderBrowserDialog1.ShowDialog(); if (result == DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; } } private void button3_Click(object sender, EventArgs e) //commands button { Process np = new Process(); np.StartInfo.FileName = "notepad.exe"; np.StartInfo.Arguments = "hbCLI.txt"; np.Start(); } private void button4_Click(object sender, EventArgs e) //options button { hbOptions options = new hbOptions(); options.ShowDialog(); } private void button5_Click(object sender, EventArgs e) //exit button { this.Close(); } private void Form1_Load(object sender, EventArgs e) { this.Resize += Form_Resize; } } }

    Read the article

  • Multiple data series in real time plot

    - by Gr3n
    Hi, I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get multiple data series into the same plot. Does anyone have a solution to this? This is the code that I've worked out this far: import os import pprint import random import sys import wx # The recommended way to use wx with mpl is with the WXAgg backend import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas, NavigationToolbar2WxAgg as NavigationToolbar import numpy as np import pylab DATA_LENGTH = 100 REDRAW_TIMER_MS = 20 def getData(): return int(random.uniform(1000, 1020)) class GraphFrame(wx.Frame): # the main frame of the application def __init__(self): wx.Frame.__init__(self, None, -1, "Usart plotter", size=(800,600)) self.Centre() self.data = [] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REDRAW_TIMER_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) # pause button self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) #self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') self.axes.set_title('Usart data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color="blue", )[0] def draw_plot(self): # redraws the plot xmax = len(self.data) if len(self.data) > DATA_LENGTH else DATA_LENGTH xmin = xmax - DATA_LENGTH ymin = 0 ymax = 4096 self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # enable grid #self.axes.grid(True, color='gray') # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=True) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): if not self.paused: newData = getData() self.data.append(newData) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('') if __name__ == '__main__': app = wx.PySimpleApp() app.frame = GraphFrame() app.frame.Show() app.MainLoop()

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >