MullionType errors in Revit API/Dynamo script - revit-api
I’m working on a Python script that takes a set of input lines and assigns a mullion to the corresponding gridline that they intersect. However, I’m getting a strange error:
that I don’t know how to correct towards the end of the script. Python is telling me that it expected a MullionType and got a Family Type (see image). I’m using a modified version of Spring Nodes’ Collector.WallTypes that collects Mullion Types instead but the output of the node is a Family Type, which the script won’t accept. Any idea how to get the Mullion Type to feed into the final Python node?
SpringNodes script:
#Copyright(c) 2016, Dimitar Venkov
# #5devene, dimitar.ven#gmail.com
import clr
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
def tolist(obj1):
if hasattr(obj1,"__iter__"): return obj1
else: return [obj1]
fn = tolist(IN[0])
fn = [str(n) for n in fn]
result, similar, names = [], [], []
fec = FilteredElementCollector(doc).OfClass(MullionType)
for i in fec:
n1 = Element.Name.__get__(i)
names.append(n1)
if any(fn1 == n1 for fn1 in fn):
result.append(i.ToDSType(True))
elif any(fn1.lower() in n1.lower() for fn1 in fn):
similar.append(i.ToDSType(True))
if len(result) > 0:
OUT = result,similar
if len(result) == 0 and len(similar) > 0:
OUT = "No exact match found. Check partial below:",similar
if len(result) == 0 and len(similar) == 0:
OUT = "No match found! Check names below:", names
The SpringNodes script outputs a Family Type, even though the collector is for Mullion Types (see above image)
Here's my script:
import clr
# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Import ToDSType(bool) extension method
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
from System import Array
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
import math
doc = DocumentManager.Instance.CurrentDBDocument
app = DocumentManager.Instance.CurrentUIApplication.Application
walls = UnwrapElement(IN[0])
toggle = IN[1]
inputLine = IN[2]
mullionType = IN[3]
wallSrf = []
heights = []
finalPoints = []
directions = []
isPrimary = []
projectedCrvs = []
keySegments = []
keySegmentsGeom = []
gridSegments = []
gridSegmentsGeom = []
gridLines = []
gridLinesGeom = []
keyGridLines = []
keyGridLinesGeom = []
projectedGridlines = []
lineDirections = []
gridLineDirection = []
allTrueFalse = []
if toggle == True:
TransactionManager.Instance.EnsureInTransaction(doc)
for w, g in zip(walls,inputLine):
pointCoords = []
primary = []
## Get curtain wall element sketch line
originLine = Revit.GeometryConversion.RevitToProtoCurve.ToProtoType( w.Location.Curve, True )
originLineLength = w.Location.Curve.ApproximateLength
## Get curtain wall element height, loft to create surface
for p in w.Parameters:
if p.Definition.Name == 'Unconnected Height':
height = p.AsDouble()
topLine = originLine.Translate(0,0,height)
srfCurves = [originLine,topLine]
wallSrf = NurbsSurface.ByLoft(srfCurves)
## Get centerpoint of curve, determine whether it extends across entire gridline
projectedCrvCenterpoint = []
for d in g:
lineDirection = d.Direction.Normalized()
lineDirections.append(lineDirection)
curveProject= d.PullOntoSurface(wallSrf)
if abs(lineDirection.Z) == 1:
if curveProject.Length >= height-.5:
primary.append(False)
else:
primary.append(True)
else:
if curveProject.Length >= originLineLength-.5:
primary.append(False)
else:
primary.append(True)
centerPoint = curveProject.PointAtParameter(0.5)
pointList = []
projectedCrvCenterpoint.append(centerPoint)
## Project centerpoint of curve onto wall surface
for h in [centerPoint]:
pointUnwrap = UnwrapElement(centerPoint)
pointList.append(pointUnwrap.X)
pointList.append(pointUnwrap.Y)
pointList.append(pointUnwrap.Z)
pointCoords.append(pointList)
finalPoints.append(pointCoords)
isPrimary.append(primary)
projectedCrvs.append(projectedCrvCenterpoint)
TransactionManager.Instance.TransactionTaskDone()
TransactionManager.Instance.EnsureInTransaction(doc)
##Gather all segments of gridline geometry
for wall in UnwrapElement(walls):
gridSegments2 = []
gridSegmentsGeom2 = []
gridLines1 = []
gridLinesGeom1 = []
for id1 in wall.CurtainGrid.GetVGridLineIds():
gridLinesGeom1.append(Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(doc.GetElement(id1).FullCurve))
gridLines1.append(doc.GetElement(id1))
VgridSegments1 = []
VgridSegmentsGeom1 = []
for i in doc.GetElement(id1).AllSegmentCurves:
VgridSegments1.append(i)
VgridSegmentsGeom1.append(Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(i,True))
gridSegments2.append(VgridSegments1)
gridSegmentsGeom2.append(VgridSegmentsGeom1)
for id2 in wall.CurtainGrid.GetUGridLineIds():
gridLinesGeom1.append(Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(doc.GetElement(id2).FullCurve))
gridLines1.append(doc.GetElement(id2))
UgridSegments1 = []
UgridSegmentsGeom1 = []
for i in doc.GetElement(id2).AllSegmentCurves:
UgridSegments1.append(i)
UgridSegmentsGeom1.append(Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(i,True))
gridSegments2.append(UgridSegments1)
gridSegmentsGeom2.append(UgridSegmentsGeom1)
gridSegments.append(gridSegments2)
gridSegmentsGeom.append(gridSegmentsGeom2)
gridLines.append(gridLines1)
gridLinesGeom.append(gridLinesGeom1)
boolFilter = [[[[b.DoesIntersect(x) for x in d] for d in z] for b in a] for a,z in zip(projectedCrvs, gridSegmentsGeom)]
boolFilter2 = [[[b.DoesIntersect(x) for x in z] for b in a] for a,z in zip(projectedCrvs, gridLinesGeom)]
##Select gridline segments that intersect with centerpoint of projected lines
for x,y in zip(boolFilter,gridSegments):
keySegments2 = []
keySegmentsGeom2 = []
for z in x:
keySegments1 = []
keySegmentsGeom1 = []
for g,l in zip(z,y):
for d,m in zip(g,l):
if d == True:
keySegments1.append(m)
keySegmentsGeom1.append(Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(m,True))
keySegments2.append(keySegments1)
keySegmentsGeom2.append(keySegmentsGeom1)
keySegments.append(keySegments2)
keySegmentsGeom.append(keySegmentsGeom2)
##Order gridlines according to intersection with projected points
for x,y in zip(boolFilter2, gridLines):
keyGridLines1 = []
keyGridLinesGeom1 = []
for z in x:
for g,l in zip(z,y):
if g == True:
keyGridLines1.append(l)
keyGridLinesGeom1.append(Revit.GeometryConversion.RevitToProtoCurve.ToProtoType(l.FullCurve,True))
keyGridLines.append(keyGridLines1)
keyGridLinesGeom.append(keyGridLinesGeom1)
##Add mullions at intersected gridline segments
TransactionManager.Instance.TransactionTaskDone()
TransactionManager.Instance.EnsureInTransaction(doc)
for x,y,z in zip(keyGridLines,keySegments,isPrimary):
projectedGridlines1 = []
for h,j,k in zip(x,y,z):
for i in j:
if i != None:
h.AddMullions(i,mullionType,k)
projectedGridlines1.append(h)
projectedGridlines.append(projectedGridlines1)
else:
None
if toggle == True:
OUT = projectedGridlines
else:
None
TransactionManager.Instance.TransactionTaskDone()
Apologies for the messiness of the code, it's a modification of another node that I've been working on. Thanks for your help.
Bo,
Your problem is rooted in how Dynamo is wrapping elements to use with its own model. That last call .ToDSType(True) is the gist of the issue. MullionType class is a subclass (it inherits properties) from a ElementType class in Revit. When Dynamo team wraps that object into a custom wrapper they only wrote a top level wrapper that treats all ElementTypes the same, hence this outputs an ElementType/FamilyType rather than a specific MullionType.
First I would suggest that you replace the line of code in your code:
mullionType = IN[3]
with:
mullionType = UnwrapElement(IN[3])
This is their built in method for unwrapping elements to be used with calls to Revit API.
If that still somehow remains an issue, you could try and retrieve the MullionType object again, this time directly in your script, before you use it. You can do so like this:
for x,y,z in zip(keyGridLines,keySegments,isPrimary):
projectedGridlines1 = []
for h,j,k in zip(x,y,z):
for i in j:
if i != None:
h.AddMullions(i,doc.GetElement(mullionType.Id),k)
projectedGridlines1.append(h)
projectedGridlines.append(projectedGridlines1)
This should make sure that you get the MullionType element before it was wrapped.
Again, try unwrapping it first, then GetElement() call if first doesn't work.
Related
How can I interpolate values from two lists (in Python)?
I am relatively new to coding in Python. I have mainly used MatLab in the past and am used to having vectors that can be referenced explicitly rather than appended lists. I have a script where I generate a list of x- and y- (z-, v-, etc) values. Later, I want to interpolate and then print a table of the values at specified points. Here is a MWE. The problem is at line 48: yq = interp1d(x_list, y_list, xq(nn))#interp1(output1(:,1),output1(:,2),xq(nn)) I'm not sure I have the correct syntax for the last two lines either: table[nn] = ('%.2f' %xq, '%.2f' %yq) print(table) Here is the full script for the MWE: #This script was written to test how to interpolate after data was created in a loop and stored as a list. Can a list be accessed explicitly like a vector in matlab? # from scipy.interpolate import interp1d from math import * #for ceil from astropy.table import Table #for Table import numpy as np # define the initial conditions x = 0 # initial x position y = 0 # initial y position Rmax = 10 # maxium range """ initializing variables for plots""" x_list = [x] y_list = [y] """ define functions""" # not necessary for this MWE """create sample data for MWE""" # x and y data are calculated using functions and appended to their respective lists h = 1 t = 0 tf = 10 N=ceil(tf/h) # Example of interpolation without a loop: https://docs.scipy.org/doc/scipy/tutorial/interpolate.html#d-interpolation-interp1d #x = np.linspace(0, 10, num=11, endpoint=True) #y = np.cos(-x**2/9.0) #f = interp1d(x, y) for i in range(N): x = h*i y = cos(-x**2/9.0) """ appends selected data for ability to plot""" x_list.append(x) y_list.append(y) ## Interpolation after x- and y-lists are already created intervals = 0.5 nfinal = ceil(Rmax/intervals) NN = nfinal+1 # length of table dtype = [('Range (units?)', 'f8'), ('Drop? (units)', 'f8')] table = Table(data=np.zeros(N, dtype=dtype)) for nn in range(NN):#for nn = 1:NN xq = 0.0 + (nn-1)*intervals #0.0 + (nn-1)*intervals yq = interp1d(x_list, y_list, xq(nn))#interp1(output1(:,1),output1(:,2),xq(nn)) table[nn] = ('%.2f' %xq, '%.2f' %yq) print(table) Your help and patience will be greatly appreciated! Best regards, Alex
Your code has some glaring issues that made it really difficult to understand. Let's first take a look at some things I needed to fix: for i in range(N): x = h*1 y = cos(-x**2/9.0) """ appends selected data for ability to plot""" x_list.append(x) y_list.append(y) You are appending a single value without modifying it. What I presume you wanted is down below. intervals = 0.5 nfinal = ceil(Rmax/intervals) NN = nfinal+1 # length of table dtype = [('Range (units?)', 'f8'), ('Drop? (units)', 'f8')] table = Table(data=np.zeros(N, dtype=dtype)) for nn in range(NN):#for nn = 1:NN xq = 0.0 + (nn-1)*intervals #0.0 + (nn-1)*intervals yq = interp1d(x_list, y_list, xq(nn))#interp1(output1(:,1),output1(:,2),xq(nn)) table[nn] = ('%.2f' %xq, '%.2f' %yq) This is where things get strange. First: use pandas tables, this is the more popular choice. Second: I have no idea what you are trying to loop over. What I presume you wanted was to vary the number of points for the interpolation, which I have done so below. Third: you are trying to interpolate a point, when you probably want to interpolate over a range of points (...interpolation). Lastly, you are using the interp1d function incorrectly. Please take a look at the code below or run it here; let me know what you exactly wanted (specifically: what should xq / xq(nn) be?), because the MRE you provided is quite confusing. from scipy.interpolate import interp1d from math import * import numpy as np Rmax = 10 h = 1 t = 0 tf = 10 N = ceil(tf/h) x = np.arange(0,N+1) y = np.cos(-x**2/9.0) interval = 0.5 NN = ceil(Rmax/interval) + 1 ip_list = np.arange(1,interval*NN,interval) xtable = [] ytable = [] for i,nn in enumerate(ip_list): f = interp1d(x,y) x_i = np.arange(0,nn+interval,interval) xtable += [x_i] ytable += [f(x_i)] [print(i) for i in xtable] [print(i) for i in ytable]
Plotting multiple lines with a Nested Dictionary, and unknown variables to Line Graph
I was able to find somewhat of an answer to my question, but it was not as nested as my dictionary and so I am really unsure how to proceed as I am still very new to python. I currently have a nested dictionary like {'140.10': {'46': {'1': '-49.50918', '2': '-50.223637', '3': '49.824406'}, '28': {'1': '-49.50918', '2': '-50.223637', '3': '49.824406'}}}: I am wanting to plot it so that '140.10' becomes the title of the graph and '46' and '28' become the individual lines and key '1' for example is on the y axis and the x axis is the final number (in this case '-49.50918). Essentially a graph like this: I generated this graph with a csv file that is written at another part of the code just with excel: [![enter image description here][2]][2] The problem I am running into is that these keys are autogenerated from a larger csv file and I will not know their exact value until the code has been run. As each of the keys are autogenerated in an earlier part of the script. As I will be running it over various files called the Graph name, and each file will have a different values for: {key1:{key2_1: {key3_1: value1, key3_2: value2, key3_3: value3}, key_2_2 ...}}} I have tried to do something like this: for filename in os.listdir(Directory): if filename.endswith('.csv'): q = filename.split('.csv')[0] s = q.split('_')[0] if s in time_an_dict: atom = list(time_an_dict[s]) ion = time_an_dict[s] for f in time_an_dict[s]: x_val = [] y_val = [] fz = ion[f] for i in time_an_dict[s][f]: pos = (fz[i]) frame = i y_val.append(frame) x_val.append(pos) '''ions = atom frame = frames position = pos plt.plot(frame, position, label = frames) plt.xlabel("Frame") plt.ylabel("Position") plt.show() #plt.savefig('{}_Pos.png'.format(s))''' But it has not run as intended. I have also tried: for filename in os.listdir(Directory): if filename.endswith('_Atom.csv'): q = filename.split('.csv')[0] s = q.split('_')[0] if s in window_dict: name = s + '_Atom.csv' time_an_dict[s] = analyze_time(name,window_dict[s]) new = '{}_A_pos.csv'.format(s) ions = list(time_an_dict.values())[0].keys() for i in ions: x_axis_values = [] y_axis_values = [] frame = list(time_an_dict[s][i]) x_axis_values.append(frame) empty = [] print(x_axis_values) for x in frame: values = time_an_dict[s][i][x] empty.append(values) y_axis_values.append(empty) plt.plot(x_axis_values, y_axis_values, label = x ) plt.show() But keep getting the error: Traceback (most recent call last): File "Atoms_pos.py", line 175, in plt.plot(x_axis_values, y_axis_values, label = x ) File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py", line 2840, in plot return gca().plot( File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py", line 1743, in plot lines = [*self._get_lines(*args, data=data, **kwargs)] File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 273, in call yield from self._plot_args(this, kwargs) File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_base.py", line 394, in _plot_args self.axes.xaxis.update_units(x) File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axis.py", line 1466, in update_units default = self.converter.default_units(data, self) File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/category.py", line 107, in default_units axis.set_units(UnitData(data)) File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/category.py", line 176, in init self.update(data) File "/Users/hxb51/opt/anaconda3/lib/python3.8/site-packages/matplotlib/category.py", line 209, in update for val in OrderedDict.fromkeys(data): TypeError: unhashable type: 'numpy.ndarray' Here is the remainder of the other parts of the code that generate the files and dictionaries I am using. I was told in another question I asked that this could be helpful. # importing dependencies import math import sys import pandas as pd import MDAnalysis as mda import os import numpy as np import csv import matplotlib.pyplot as plt ################################################################################ ############################################################################### Directory = '/Users/hxb51/Desktop/Q_prof/Displacement_Charge/Blah' os.chdir(Directory) ################################################################################ ''' We are only looking at the positions of the CLAs and SODs and not the DRUDE counterparts. We are assuming the DRUDE are very close and it is not something that needs to be concerned with''' def Positions(dcd, topo): fields = ['Window', 'ION', 'ResID', 'Location', 'Position', 'Frame', 'Final'] with open('{}_Atoms.csv'.format(s), 'a') as d: writer = csv.writer(d) writer.writerow(fields) d.close() CLAs = u.select_atoms('segid IONS and name CLA') SODs = u.select_atoms('segid IONS and name SOD') CLA_res = len(CLAs) SOD_res = len(SODs) frame = 0 for ts in u.trajectory[-10:]: frame +=1 CLA_pos = CLAs.positions[:,2] SOD_pos = SODs.positions[:,2] for i in range(CLA_res): ids = i + 46 if CLA_pos[i] < 0: with open('{}_Atoms.csv'.format(s), 'a') as q: new_line = [s,'CLA', ids, 'Bottom', CLA_pos[i], frame,10] writes = csv.writer(q) writes.writerow(new_line) q.close() else: with open('{}_Atoms.csv'.format(s), 'a') as q: new_line = [s,'CLA', ids, 'Top', CLA_pos[i], frame, 10] writes = csv.writer(q) writes.writerow(new_line) q.close() for i in range(SOD_res): ids = i if SOD_pos[i] < 0: with open('{}_Atoms.csv'.format(s), 'a') as q: new_line = [s,'SOD', ids, 'Bottom', SOD_pos[i], frame,10] writes = csv.writer(q) writes.writerow(new_line) q.close() else: with open('{}_Atoms.csv'.format(s), 'a') as q: new_line = [s,'SOD', ids, 'Top', SOD_pos[i], frame, 10] writes = csv.writer(q) writes.writerow(new_line) q.close() csv_Data = pd.read_csv('{}_Atoms.csv'.format(s)) filename = s + '_Atom.csv' sorted_df = csv_Data.sort_values(["ION", "ResID", "Frame"], ascending=[True, True, True]) sorted_df.to_csv(filename, index = False) os.remove('{}_Atoms.csv'.format(s)) ''' this function underneath looks at the ResIds, compares them to make sure they are the same and then counts how many times the ion flip flops around the boundaries''' def turn_dict(f): read = open(f) reader = csv.reader(read, delimiter=",", quotechar = '"') my_dict = {} new_list = [] for row in reader: new_list.append(row) for i in range(len(new_list[:])): prev = i - 1 if new_list[i][2] == new_list[prev][2]: if new_list[i][3] != new_list[prev][3]: if new_list[i][2] in my_dict: my_dict[new_list[i][2]] += 1 else: my_dict[new_list[i][2]] = 1 return my_dict def plot_flips(f): dict = turn_dict(f) ions = list(dict.keys()) occ = list(dict.values()) plt.bar(range(len(dict)), occ, tick_label = ions) plt.title("{}".format(s)) plt.xlabel("Residue ID") plt.ylabel("Boundary Crosses") plt.savefig('{}_Flip.png'.format(s)) def analyze_time(f, dicts): read = open(f) reader = csv.reader(read, delimiter=",", quotechar='"') new_list = [] keys = list(dicts.keys()) time_dict = {} pos_matrix = {} for row in reader: new_list.append(row) fields = ['ResID', 'Position', 'Frame'] with open('{}_A_pos.csv'.format(s), 'a') as k: writer = csv.writer(k) writer.writerow(fields) k.close() for i in range(len(new_list[:])): if new_list[i][2] in keys: with open('{}_A_pos.csv'.format(s), 'a') as k: new_line = [new_list[i][2], new_list[i][4], new_list[i][5]] writes = csv.writer(k) writes.writerow(new_line) k.close() read = open('{}_A_pos.csv'.format(s)) reader = csv.reader(read, delimiter=",", quotechar='"') time_list = [] for row in reader: time_list.append(row) for j in range(len(keys)): for i in range(len(time_list[1:])): if time_list[i][0] == keys[j]: pos_matrix[time_list[i][2]] = time_list[i][1] time_dict[keys[j]] = pos_matrix return time_dict window_dict = {} for filename in os.listdir(Directory): s = filename.split('.dcd')[0] fors = s + '.txt' topos = '/Users/hxb51/Desktop/Q_prof/Displacement_Charge/topo.psf' if filename.endswith('.dcd'): print('We are starting with {} \n '.format(s)) u = mda.Universe(topos, filename) Positions(filename, topos) name = s + '_Atom.csv' plot_flips(name) window_dict[s] = turn_dict(name) continue time_an_dict = {} for filename in os.listdir(Directory): if filename.endswith('.csv'): q = filename.split('.csv')[0] s = q.split('_')[0] if s in window_dict: name = s + '_Atom.csv' time_an_dict[s] = analyze_time(name,window_dict[s]) for filename in os.listdir(Directory): if filename.endswith('.csv'): q = filename.split('.csv')[0] s = q.split('_')[0] if s in time_an_dict: atom = list(time_an_dict[s]) ion = time_an_dict[s] for f in time_an_dict[s]: x_val = [] y_val = [] fz = ion[f] for i in time_an_dict[s][f]: pos = (fz[i]) frame = i y_val.append(frame) x_val.append(pos) '''ions = atom frame = frames position = pos plt.plot(frame, position, label = frames) plt.xlabel("Frame") plt.ylabel("Position") plt.show() #plt.savefig('{}_Pos.png'.format(s))''' Everything here runs well except this last bottom block of code. That deals with trying to make a graph from a nested dictionary. Any help would be appreciated! Thanks!
I figured out the answer: for filename in os.listdir(Directory): if filename.endswith('_Atom.csv'): q = filename.split('.csv')[0] s = q.split('_')[0] if s in window_dict: name = s + '_Atom.csv' time_an_dict[s] = analyze_time(name,window_dict[s]) new = '{}_A_pos.csv'.format(s) ions = list(time_an_dict[s]) plt.yticks(np.arange(-50, 50, 5)) plt.xlabel('Frame') plt.ylabel('Z axis position(Ang)') plt.title([s]) for i in ions: x_value = [] y_value = [] time_frame =len(time_an_dict[s][i]) +1 for frame in range(1,time_frame): frame = str(frame) x_value.append(int(frame)) y_value.append(float(time_an_dict[s][i][frame])) plt.plot(x_value, y_value, label=[i]) plt.xticks(np.arange(1, 11, 1)) plt.legend() plt.savefig('{}_Positions.png'.format(s)) plt.clf() os.remove("{}_A_pos.csv".format(s)) From there, with the combo of the other parts of the code, it produces these graphs: For more than 1 file as long as there is more '.dcd' files.
Python: Build Graphs with set of sets adjacency list
Hello this is my first post and I'm not fluent in English, so forgive me if I do any wrong post protocol .... so, I have this current implementation of a graph, through an adjacency matrix: class GFG: def __init__(self,graph): self.graph = graph from which I start like this: my_shape = (N,M) bpGraph = np.zeros(my_shape) and add edges like this: vertex_a = 2 vertex_b = 5 bpGraph [vertex_a, vertex_b] = 1 g = GFG(bpGraph) and check for an edge like this: if bpGraph [vertice_a, vertice_b]: do something... But this type of structure can take a lot of space if I have a lot of vertices, so I would like to switch to a set map class GFG: def __init__(self,N,M): mysetdict = { "dummy_a": {"dummy_b","dummy_c"}, } self.graph = mysetdict def add_edges(self,N,M): N_set = {} if str(N) in self.graph: N_set = self.graph[str(N)] N_set.add(str(M)) self.graph[str(N)] = N_set def check_edges(self,N,M): return str(M) in self.graph[str(N)] When I try to add a vertex I get this error: g = GFG (3,4) g.add_edges (0, 0) AttributeError: 'dict' object has no attribute 'add' ---> 16 N_set.add(str(M)) im trying many ways to build this set and check if a entry exists before add a vertex_a to do a edge with vertex_b, but all my tryes results in a atribute error. any suggestions?
solved, just doing N_set = set() def add_edges(self,N,M): N_set = set() if str(N) in self.m_graph: N_set = self.m_graph[str(N)] N_set.add(str(M)) self.m_graph[str(N)] = N_set
IndexError at /new-watch-hour-graph/
def getNewWatchedCountGraph(requests): data = Video.getNewWatchedCountGraph(requests) data = json.loads(data) # print(data) x = [] m = [] bg = {} res = {} monthnumbers = [] currentMonth = datetime.datetime.now().month for item in data: seconds = int(item['count']) x.append(seconds) mydate = datetime.datetime.strptime(item['_id'], "%Y-%m") monthnumbers.append(mydate.month) m.append(mydate.strftime("%B")) startMonths = monthnumbers[0] #line 116 endMonths = currentMonth+1 data = [] mon = [] for months in range(startMonths,endMonths): if months not in monthnumbers: mon.append(calendar.month_name[months]) data.append(0) else: mon.append(calendar.month_name[months]) monthIndex = monthnumbers.index(months) data.append(x[monthIndex]) res['series_name'] = "Views" res['series'] = list(data) res['xdata'] = list(mon) restrn_response = dumps(res) return HttpResponse(restrn_response) I have made this function to show the graph of total number of views. It is working fine in my local server. But showing List index out of range in main server at line no 116. Where am i doing wrong?
This happens because monthnumbers is empty. Given that it’s being filled while iterating over data, I think the loop doesn’t even start because data is empty.
Numpy shape not including classes
I want to create a dataset(data.npy) that has the same format as cifar10. The sample omniglot dataset contains data = [0001_01.png,0001_02.png,0001_03.png,0001_04.png,0002_01.png,0002_02.png,0002_03.png] class_name,filename = data[0].split('_') Each file is append with class.There are 1600 classes and each class has 20 samples. The expected dataset(data.npy) shape is (1600,20,784) But the shape i got is (1,20,784). Below given is the snippet classes = [] examples = [] prev = files[0].split('_')[0] for f in files: cur_id = f.split('_')[0] cur_pic = misc.imresize(misc.imread('new_data/' + f),[28,28]) cur_pic = (np.float32(cur_pic)/255).flatten() if prev == cur_id: examples.append(cur_pic) else: classes.append(examples) examples = [cur_pic] prev = cur_id np.save('data',np.asarray(classes)) Any suggestions would be greatly helpful. The above code is taken from https://github.com/zergylord/oneshot